Fragment without activity

后端 未结 7 1763
夕颜
夕颜 2020-12-29 06:14

I have been asked an interview question: Can a fragment exist without activity? I searched for answers but didn\'t get a proper answer and explanation. Can

相关标签:
7条回答
  • 2020-12-29 06:21

    Yes, you can do this anywhere:

    new YourFragment();
    

    As fragments must have a parameter-less constructor.

    However its lifecycle doesn't kick in until it is attached. So onAttach, onCreate, onCreateView, etc. are only called when it is attached. So most fragments do nothing until they are attached.

    0 讨论(0)
  • 2020-12-29 06:23

    Android app must have an Activity or FragmentActivity that handles the fragment.

    Fragment can't be initiated without Activity or FragmentActivity.

    0 讨论(0)
  • 2020-12-29 06:24

    A Fragment can exist independently, but in order to display it, you need the help of an Activity. The Activity will act like a container for the Fragment(s).

    0 讨论(0)
  • 2020-12-29 06:26

    I read above top rated answer , i am not disagreeing but android already provides to make independent fragment without activity DialogFragment , which extends fragment . if you want show in full screen first extends DialogFragment then

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NO_FRAME, android.R.style.Theme_Holo_Light);
    
    }
    
    0 讨论(0)
  • 2020-12-29 06:28

    A fragment is not required to be a part of the Activity layout; you may also use a fragment without its own UI as an invisible worker for the Activity but it needs to be attached to an Activity in order to appear on the screen.

    0 讨论(0)
  • 2020-12-29 06:39

    As soon as you create an instance of the Fragment class, it exists, but in order for it to appear on the UI, you must attach that fragment to an activity because a fragment's lifecycle runs parallel to an activity's lifecycle. Without any call to Activity's onCreate(), there will be no call for onAttach(), onCreate(), onCreateView() and onActivityCreated() of fragment and so it can't be started.

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