onActivityResult For Fragment

前端 未结 4 2149
清歌不尽
清歌不尽 2020-12-30 19:32

I currently have a base activity which is hosting a single fragment. Inside the fragment I have a method which starts the contact chooser.

private void choo         


        
4条回答
  •  生来不讨喜
    2020-12-30 20:12

    The onActivityCreated of the fragment serves another purpose:

    Called when the fragment's activity has been created and this fragment's view hierarchy instantiated. It can be used to do final initialization once these pieces are in place, such as retrieving views or restoring state. It is also useful for fragments that use setRetainInstance(boolean) to retain their instance, as this callback tells the fragment when it is fully associated with the new activity instance. This is called after onCreateView(LayoutInflater, ViewGroup, Bundle) and before onViewStateRestored(Bundle).

    This is extracted from the documentation

    Mainly with a fragment you will inflate and return the view in the onCreateView, do the view operations (like set an ListAdapter in a ListView) in the onViewCreated. And perform the initialization operations (like show a welcome dialog or something like that) in the onActivityCreated.

    You have, several choices, I'm not pretty sure about wich is better for your problem:

    • What I would do will'be do a findFragmentById in the onActivityResult of the activity, and if the fragment isn't null, execute a method that handles the come back from the contact list in the fragment.

    • Another way of do it is fire a BroadCastReceiver in the onActivityResult of the activity, and register you fragment to listen that broadcast. But I think that this is too messy for something so simple.

    • Finally, like the first one, if you don't have a fragment with an id, you can instantiate the fragment in your activity, save a reference, and send it a message when the onActivityResult of the activity is executed.

    I hope that something of this helps you.

提交回复
热议问题