Tim
Tim

Reputation: 13258

Android TabListener: onTabSelected - add fragment to back stack

I use in my Android application a TabListener similar to this one: http://developer.android.com/guide/topics/ui/actionbar.html#Tabs

My onTabSelected implementation:

public void onTabSelected(Tab tab, FragmentTransaction ft) {
    Fragment preInitFrag = mActivity.getFragmentManager().findFragmentByTag(mTag);
    if (preInitFrag == null) {
        mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
        ft.add(android.R.id.content, mFragment, mTag);
    } else {
        ft.attach(preInitFrag);
    }
}

Every time a tab is selected, I want to add it to the back stack. How can I do this? Using the parameter ft with ft.addToBackStack("test"), it does not work. It throws a fatal exception:

java.lang.RuntimeException:
    Unable to start activity ComponentInfo{.../...BaseActivity}:
java.lang.IllegalStateException:
    This FragmentTransaction is not allowed to be added to the back stack.

Upvotes: 2

Views: 5282

Answers (2)

Vishnu Prabhu
Vishnu Prabhu

Reputation: 459

Create you own FragmentTrasaction inside the onTabChanged callback, and try commit(); Check the below link.

FragmentTransaction is not allowed to be added to back stack?

Upvotes: 0

Barend
Barend

Reputation: 17444

The ActionBar guide that you linked to in your question has this to say about the back stack (In the "caution" section below the tab listener sample code):

You also cannot add these fragment transactions to the back stack.

The guide doesn't explain why, but what you want is not supported. You'll have to keep tag history in some other way, or don't keep tab history at all.

Upvotes: 3

Related Questions