简体   繁体   中英

How can I maintain state when switching between action bar tabs / fragments?

I have a number of fragments attached to the Android action bar as tabs. I can switch between them without problems. However, if one of the fragments has a TextView (for example), and I alter the text of that TextView , the new text is not kept if I switch to another tab and back.

I've tried overriding onSaveInstanceState() , but it appears it is not called when I switch tabs, as savedInstanceState is null every time onActivityCreated() is called (ie every time that tab is reopened).

I looked into altering onPause() such that it calls onSaveInstanceState() , but onPause() doesn't have access to the state bundle, so I don't see how I can do that.

What is the best way to keep state in a tab when going back and forth between tabs?

When you are switching between fragments, don't detach fragments just hide. Example:

@Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
      FragmentManager fm = getFragmentManager(); 
      if(fm.findFragmentByTag(tab.getTag().toString()) == null){
           ft = fm.beginTransaction();
           FragmentContent contentfrag = new FragmentContent();
           ft.add(R.id.framelayout, contentfrag, tab.getTag().toString());
           ft.addToBackStack("BackStack" + tab.getTag().toString());
       }
       else{
           Fragment frag = fm.findFragmentByTag(tab.getTag().toString());
           ft.show(frag);
      }
}

    @Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        Fragment frag = this.getFragmentManager().findFragmentByTag(tab.getTag().toString());
    ft.hide(frag);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM