How can I maintain state when switching between action bar tabs / fragments?
android, java
Solution
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);
}
Problem
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 (i.e. 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?