1

I'm trying to implement a tab bar with fragments and RadioGroup

i switch fragments like on checked Change of radiogroup like this (saw something like this in sdk examples)

publi

 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 happen attached fragment is created from scratch i.e. called onCreate and so on..

is there any way to preserve fragments from creating over and over again within an activity? also i don't want the back button could switch fragments back;

Korniltsev Anatoly
  • 3,676
  • 2
  • 26
  • 37

1 Answers1

8

Instead of using the methods FragmentTransaction.attach() and FragmentTransaction.detach() you could use FragmentTransaction.show() and FragmentTransaction.hide(). You would need to also alter some of the surrounding code you gave in the example above but I'll leave that as an exercise for your good-self.

D-Dᴙum
  • 7,689
  • 8
  • 58
  • 97