onCreate() and onCreateView() invokes a lot more than required (Fragments)

前端 未结 6 1981
不知归路
不知归路 2021-01-30 10:19

Can somebody explain why the onCreate() and onCreateView() are being invoked so many times which increments with each orientation change?

Here

相关标签:
6条回答
  • 2021-01-30 11:01

    I can't point to the documentation which explains this, but the solution is to only create and add the fragment when the activity first loads, like this:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        if (savedInstanceState == null) {
            Fragment fg = new Right();
            getFragmentManager().beginTransaction().add(R.id.right_frag, fg)
                .commit();
        }
        Log.i("Main", "onCreate()");
    }
    
    0 讨论(0)
  • 2021-01-30 11:04

    main class should extend FragmentActivity and not Activity.

    also look up Activity life cycle on the android doc

    0 讨论(0)
  • 2021-01-30 11:05

    Looks like you have so many fragments there! If you define fragment in xml file you can not define "it" again in your code! There are two ways how to define fragmets: dynamiclly (in your code) and statically (in your xml)! Take a look here: http://marakana.com/s/post/1250/android_fragments_tutorial

    It is really good tutorial.

    0 讨论(0)
  • 2021-01-30 11:05

    An orientation change causes the system to go through the process of saving instance state, pausing, stopping, destroying, and then creating a new instance of the activity with the saved state. So this is the reason why there is so much onCreate and onCreateView calls.

    I do not think the if (savedInstanceState == null) condition in the onCreate method is a good idea; the state-saving mechanism will not work properly...

    0 讨论(0)
  • 2021-01-30 11:10

    If you don't use different layouts for different orientations, I think that you should use android:configChanges="orientation" in your manifest. http://developer.android.com/guide/topics/manifest/activity-element.html#config

    0 讨论(0)
  • 2021-01-30 11:11

    Yes, this is very bad documented. The explanation is that when the Activity is restored it will "auto-magically" restore the Fragments that were added in it, so adding another Fragment in your Activity will basically add another new Fragment on top of the previous Fragment\s that are actually restored by Android.

    This behavior is definitely intended, and the approach suggested by @Joris Wit is the correct one.

    Also this is very helpful when you think about it, because let's say you have a stack of Fragments added one on top of each other, and you can navigate back to them using the back key. In the case of a rotation, if Android would not restore the backstack of Fragments you will lose all of them, or you will have to implement some mechanism to keep track of your Fragment stack.

    0 讨论(0)
提交回复
热议问题