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

I have several snippets attached to the Android action bar as tabs. I can switch between them without any problems. However, if one of the fragments has a TextView (for example), and I change the text of this TextView , the new text is not saved if I switch to another tab and vice versa.

I tried to override onSaveInstanceState() , but it doesn't seem to be called when I switch tabs, since savedInstanceState is null every time onActivityCreated() is onActivityCreated() (i.e. every time this tab opens again).

I was looking for a change onPause() that calls onSaveInstanceState() , but onPause() does not have access to the status package, so I don’t see how to do it.

What is the best way to keep state on a tab when switching between tabs?

+4
source share
1 answer

When you switch between fragments, do not disconnect fragments only to 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); } 
+10
source

All Articles