droidev
droidev

Reputation: 7390

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();
    }

Upvotes: 0

Views: 1083

Answers (2)

Georgy
Georgy

Reputation: 384

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

Upvotes: 0

Gordak
Gordak

Reputation: 2070

Keep the name of the class of your Fragments in the Bundle.

Then recreate your Fragment with the name of the class, using the static method instantiate.

String name = savedInstanceState.getString(CURRENT_FRAGMENT_TAG);
Fragment fragment = Fragment.instantiate (Activity.this, "com.example." + name);

The method expects the full name (package included).

Upvotes: 2

Related Questions