How to keep fragments rest

I am trying to implement a tab bar with fragments and RadioGroup

i switch fragments, for example, to the marked replacement of the radio group (see examples in the sdk examples)

tse

void onCheckedChanged(RadioGroup radioGroup, int id) { TabInfo newTab = mContent.get(id); if (newTab != lastTab) { FragmentTransaction transaction = mActivity.getSupportFragmentManager().beginTransaction(); if (lastTab != null && lastTab.fragment != null) { transaction.detach(lastTab.fragment); } if (newTab.fragment == null) { newTab.fragment = Fragment.instantiate(mActivity, newTab.getTag()); transaction.add(mContainerId, newTab.fragment); } else { transaction.attach(newTab.fragment); } lastTab = newTab; transaction.setCustomAnimations(R.anim.tab_transaction, R.anim.tab_transaction); transaction.commit(); } } 

but every time this happens, the attached fragment is created from scratch, i.e. calls onCreate etc.

Is there a way to keep fragments from creating again and again as part of an action? I also don’t want the button back to be able to switch fragments back;

+1
source share
1 answer

Instead of using the FragmentTransaction.attach () and FragmentTransaction methods . detach () you can use FragmentTransaction.show () and FragmentTransaction.hide () . You will also need to change part of the surrounding code that you specified in the example above, but I will leave this as an exercise for your good self.

+7
source

All Articles