7

Can someone explain to me or maybe point a link or an example of how one should handle screen orientation when it comes to fragments. The problem that I am having at the moment is that I have an app with an action bar with three tabs. Each tab containing one fragment. So when i flip the device, only the one fragment that I set as selected using

actionbar.setSelectedNavigationItem(1) 

is shown (for no confusion, the other tabs are visible, but when I click on them nothing happens, they can't be selected and shown. Their content is never shown). Is there something that is done in these cases? Can someone give me an advice, I would appreciate it. Thank u.

1 Answer 1

13

I had the same problem and found a solution here: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/FragmentTabs.html

Problem is that there are already fragments for the tabs from the previously saved state. You have to deactivate them.

Here's the code-snippet for the constructor of your TabListener:

public TabListener(Activity activity, String tag, Class<T> clz, Bundle args) {
        mActivity = activity;
        mTag = tag;
        mClass = clz;
        mArgs = args;

        // Check to see if we already have a fragment for this tab, probably
        // from a previously saved state.  If so, deactivate it, because our
        // initial state is that a tab isn't shown.
        mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
        if (mFragment != null && !mFragment.isDetached()) {
            FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction();
            ft.detach(mFragment);
            ft.commit();
        }
    }

Hope I could help you.

3
  • I figured the same out, couple of days ago. But solved it a little more differently. In the onDestroyView method in the fragments, I call remove for that particular fragment so it won't be any fragments from previous states. But your way solves the problem too, I imagine. So thank u!
    – Sandra
    Apr 6, 2012 at 7:50
  • Well explained, makes sense, solves a specific common problem. Many thanks. A+ Aug 2, 2012 at 4:11
  • 1
    Thanks! BTW, I use hide/show instead of detach/attach is some places, to avoid fragment view recreation (sometimes it's long). And it does work then too. Oct 17, 2013 at 10:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.