Search code examples
androidandroid-fragmentsandroid-orientation

Retain Current Visible Fragment After Orientation Changes


In my application I have 3 Fragments. suppose fragment1, fragment2, and Fragment3. these three fragments hosted on single activity. there is a Navigation drawer available to navigate each fragment. and Fragment1 is the default fragment, ie., Fragment1 is visible when the application starts. the problem is when the orientation of phone changes the current visible fragment goes out and the default fragment shows, because the activity restarts. I am keeping a the tag of current visible fragment's tag in bundle, and checks in onCreate method. but I cant create Fragment object of corresponding fragment by tag.

onCreate

if (savedInstanceState == null) {
            mFragment = new Fragment1();
            showFragment(mFragment, FRAGMENT1_TAG);
        } else {
            String tag = savedInstanceState.getString(CURRENT_FRAGMENT_TAG);
            mFragment = mFragmentManager.findFragmentByTag(tag);

            if (mFragment != null)
                mFragmentManager.beginTransaction().replace(R.id.content_frame, mFragment, tag).commit();
            else
                Toast.makeText(getBaseContext(), "Something went wrong, please restart application", Toast.LENGTH_SHORT).show();
        }

onSaveInstanceState

String fragmentTag = mFragmentManager.findFragmentById(R.id.content_frame).getTag();
        dataOut.putString(CURRENT_FRAGMENT_TAG, fragmentTag);

when the orientation changes I am getting a null pointer exception, that is the mFragment is null, how can I resolve this

UPDATE

 public static void showFragment(Fragment fragment, String tag) {
        mFragmentTag = tag;

        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.content_frame, fragment, mFragmentTag);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

Solution

  • The easiest way to do it is to prevent the activity from recreating by setting android:configChanges="screenSize|orientation" in your manifest file.

    UPDATE

    You need to call to: super.onSaveInstanceState(outState); when overriding the onSaveInstanceState method