onCreateView method gets called when? and How many times in Activity life cycle?

后端 未结 4 934
甜味超标
甜味超标 2020-12-13 14:06

I wrote a little program looking like this:

package com.example.lifecycle;

import android.app.Activity;
import android.content.Context;
import android.os.Bu         


        
相关标签:
4条回答
  • 2020-12-13 14:15

    Android Framework uses mechanism of Dependencies injection When layout file is inflated.I think due to this onCreateView is called so many times.Formula for this might be as below

    • no of view in layout xml == no of calls to onCreateView

    Try to remove setContentView and see how many times onCreateView is called.You might get some insights into it.

    0 讨论(0)
  • 2020-12-13 14:17

    You can monitor the reason onCreateView gets Called from a log file :

    add inside your onCreateView method this :

    Log.d("TAG", "onCreateView event : " + name);
    

    such as my logcat produce this ;

    onCreateView : LinearLayout
    onCreateView : ViewStub
    onCreateView : FrameLayout
    onCreateView : android.support.v7.widget.ActionBarOverlayLayout
    onCreateView : android.support.v7.widget.ContentFrameLayout
    onCreateView : android.support.v7.widget.ActionBarContainer
    onCreateView : android.support.v7.widget.Toolbar
    onCreateView : android.support.v7.widget.ActionBarContextView
    onCreateView : LinearLayout
    
    0 讨论(0)
  • 2020-12-13 14:19

    onCreateView calls = number of views in layout (create each view)

    0 讨论(0)
  • 2020-12-13 14:21

    You have extended your class with Activity. That means your class' lifecycle would be as below.

    enter image description here

    So, onCreateView is not a lifecycle method for activity. It's just a member method which will be used for specified tasks as said in doc.

    Standard implementation of android.view.LayoutInflater.Factory.onCreateView used when inflating with the LayoutInflater returned by getSystemService. This implementation does nothing and is for pre-android.os.Build.VERSION_CODES.HONEYCOMB apps. Newer apps should use onCreateView(View, String, Context, AttributeSet).

    To rely on the call of onCreateView() in an Activity is bad programming.

    If you were using Fragment extended to your class and have written onCreateView() method, then it would have been called only twice after your onAttach() and onDestroyView() if you are still on same fragment.

    See this diagram.

    enter image description here

    Here, it's a method of lifecycle for Fragment.

    So, you are testing with wrong assumptions. That's all!

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