Arun Arun - 9 days ago 5
Android Question

Fragments get loaded every time i switch tab, need efficient method

These are the screenshots of my application,

http://i.stack.imgur.com/3GYAc.png ==> after loading the list from remote server the list is populated.

The problem for me is this,

When i move to the title Android - third tab(refer link) and switch back to java tab, the data is loading again.

How to make it load it single time and save it, so that it doesn't load every time?

The main activity is fragmentactivity which listens to tabadapter for changes in tabs.

This one is page adapter..

public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}

@Override
public Fragment getItem(int index) {

switch (index) {
case 0:
// Top Rated fragment activity
return new TopRatedFragment2();

case 1:
// Games fragment activity
return new GamesFragment();
case 2:
// Movies fragment activity
return new MoviesFragment();
}

return null;
}


This one is fragmentActivity which uses page adapter

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.messages_layout);

// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener((TabListener) this));
}

/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

@Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}

@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}

@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
@Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub


}
@Override
public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
int position = mAdapter.getItemPosition(arg0);//;findItemPosition(arg0.getPosition());
viewPager=(getCurrentFocus()).ggetFragment(arg0, null);
viewPager.setCurrentItem(arg0.getPosition());

}

Answer

According to revision 4 of the Support Package, a method was added to ViewPager which allows you to specify the number of offscreen pages to use, rather than the default which is 1. so you can load page rightside when move.

In your case, you want to specify 2, so that when you are on the third page, the first one is not destroyed, and vice-versa.

mViewPager = (ViewPager)findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(2);

Thats it....

Comments