Reputation: 1089
I've got a ViewPager
with 4 tabs.
I'm using a custom adapter that extends FragmentPagerAdapter
.
The problem is that when I change the tab, the first Fragment
gets created again although it's not the currently visible.
Moreover, this only happens after changing the tab for the fourth time. E.g. tab1 -> tab2 -> tab3=> onStop
from tab1 is called. -> tab2 => onCreateView
from tab1 is called (onAttach
is not called).
I want to avoid this. I need all tabs to remain always in their state even when they are not currently displayed. How can I do this?
Upvotes: 6
Views: 6984
Reputation: 52366
Viewpager has one public method named setOffScreenPageLimit which indicates the number of pages that will be retained to either side of the current page in the view hierarchy in an idle state.
Activity:
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = findViewById(R.id.container);
mViewPager.setOffscreenPageLimit(3); // change your number here
mViewPager.setAdapter(mSectionsPagerAdapter);
Upvotes: 1
Reputation: 1089
It's been as easy as using method setOffscreenPageLimit()
from ViewPager
.
Upvotes: 24
Reputation: 10946
When you instantiate the fragment, call setRetainInstance(true)
. This will retain the instance state of the fragment. onCreateView
will still be called and you will need to make sure that you re use the saved state and just render the views without loading any data again, e.g. by using a boolean
to represent if your fragment has already been initialized.
You would do something like this:
public static class MyAdapter extends FragmentPagerAdapter {
@Override
public Fragment getItem(int position) {
MyFragment myFragment = new MyFragment();
myFragment.setRetainInstance(true);
return myFragment;
}
}
class MyFragment extends Fragment {
.
.
.
boolean initialized = false;
ArrayList<MyData> myData = null;
void onCreate(...) {
if (initialized) {
renderViews();
} else {
initialized = true;
loadData();
renderViews();
}
}
}
You don't need to implement onSaveInstanceState()
. It will be handled automatically.
Upvotes: 0