I currently have a fragment in an overlay. This is for signing in to the service. In the phone app, each of the steps I want to show in the overlay are their own screens and activities. There are 3 parts of the sign-in process and each had their own activity that was called with startActivityForResult().
Now I want to do the same thing using fragments and an overlay. The overlay will show a fragment corresponding to each activity. The problem is that these fragments are hosted in an activity in the Honeycomb API. I can get the first fragment working, but then I need to startActivityForResult(), which isn't possible. Is there something along the lines of startFragmentForResult() where I can kick off a new fragment and when it's done have it return a result to the previous fragment?
My 2 cents.
I switch beween fragments by swapping an old fragment with a new one using hide and show/add (existing/new). So this answer is for devs who use fragments like I do.
Then I use the
onHiddenChanged
method to know that the old fragment got switched to back from the new one. See code below.Before leaving the new fragment, I set a result in a global parameter to be queried by the old fragment. This is a very naive solution.
There is an Android library - FlowR that allows you to start fragments for results.
Starting a fragment for result.
Handling results in the calling fragment.
Setting the result in the Fragment.
All of the Fragments live inside Activities. Starting a Fragment for a result doesn't make much sense, because the Activity that houses it always has access to it, and vice versa. If the Fragment needs to pass on a result, it can access its Activity and set its result and finish it. In the case of swapping Fragments in a single Activity, well the Activity is still accessible by both Fragments, and all your message passing can simply go through the Activity.
Just remember that you always have communication between a Fragment and its Activity. Starting for and finishing with a result is the mechanism for communication between Activities - The Activities can then delegate any necessary information to their Fragments.
A solution using interfaces (and Kotlin). The core idea is to define a callback interface, implement it in your activity, then call it from your fragment.
First, create an interface
ActionHandler
:Next, call this from your child (in this case, your fragment):
Finally, implement this in your parent to receive the callback (in this case, your Activity):
You can use EventBus. It simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality.
In your fragment you can call getActivity(). This will give you access to the activity that created the fragment. From there you can call your customize method to set the values or to pass the values.