سؤال

I have an Activity with a NavigationDrawer and a Fragment which is created when I click on the NavigationDrawer. When I create the Fragment, I pass to it some arguments. When I rotate the screen, the activity is recreated, the navigationdrawer is recreated and also the Fragment. After this operations, the fragment is recreated, but without arguments. I want understand who creates the Fragment the second time... Can anyone help me?

هل كانت مفيدة؟

المحلول 2

Use this in your manifest with Fragment activity:

      android:configChanges="orientation|keyboardHidden|screenSize"

However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device)

نصائح أخرى

I ran into a similar issue when trying to restore the video player state (play or pause) and position (time elapsed) after changing the screen orientation. When I rotate the screen once, I noticed that onCreateView in the fragment activity is called twice. When it is rotated twice, onCreateView is called three time - and so on. The last call somehow forgets the states I saved in onSaveInstanceState (in the fragment activity).

Upon digging around, I found the answer I was looking for. In the activity that adds the fragment, I needed to check if savedInstanceState is null. Only if it is null should you add the fragment.

For example:

if (savedInstanceState == null) {
    fragmentManager = getSupportFragmentManager();

    FragmentActivity fragment = new FragmentActivity();

    fragmentManager.beginTransaction()
         .add(R.id.fragment_container, fragment)
         .commit();
}

More information can be found here: Android Fragment lifecycle over orientation changes

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top