Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ViewPager with tabs save state

I'm implementing a ViewPager with tabs similar to implementation provided by Google here.

My app has the following behaviour. My ViewPager has 3 "pages" (fragA, fragB, fragC) and I'm implementing 3 tabs on top of the ViewPager. The differece between google's implementation and mine is that the tabs aren't used to navigate between fragments. As an example, pressing one of my tabs, loads a different set of data on the visible fragment. I can have fragA with tab3 selected, fragB with tab2 selected and fragCwith tab1 selected.

When I swipe between the fragments I want to maintain the state that is, the tab that is currently selected. I'm achiving this with this code:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser && mTabHost != null) {
        if (mTabHost.getCurrentTab() != selectedTimePeriod) {
            mTabHost.setCurrentTab(selectedTimePeriod);
        }
    }
}

I have the above code in the 3 fragments and this is working as expected almost every time but unfortunatly in some situation, that i can't even exactly reproduce since it happens randonly, the state isn't maintained.

Whats the proper way to save the state of my tabs (for example between screen rotation) between Viewpager swipes?

like image 949
Favolas Avatar asked May 24 '26 05:05

Favolas


1 Answers

You can use

viepagerObj.setOffscreenPageLimit(2)

This will load fragments and keep it in memory. For example in you case at the time of launch apart from the first one(fragC) the next 2 fragments(fragB and fragA) will be loaded and saves in memory. By default the value is 1, means frag C + the next fragment(fragB) is loaded and when you swipe right fragA will load removing fragC and vice versa.

like image 154
droid kid Avatar answered May 26 '26 20:05

droid kid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!