I create an application as below:
Main activity includes FragmentTabHost
which includes two ContainerFragments
which include two Fragments separately.
Now I startActivityForResult
from UserFragment
, but onActivityResult
in UserFragment
cannot be called! What's wrong? How to resolve?
The project in https://github.com/VictorS-Zhao/TabHostAndNestedFragment.
Thanks in advance!
Supplement:
This is a strange behavior, the 1st nested fragment Community Fragment's onActivityResult
can be called every time, but the 2nd nested fragment User Fragment's cannot be called. When startActivityForResult
from UserFragment
, but the onActivityResult
in CommunityFragment
is called.
Solution:
Finally I found solution in onActivityResult() not called in new nested fragment API
According to this answer, should override onActivityResult
in ContainerFragment
, and use getParentFragment().startActivityForResult
in UserFragment
. That's nice!
Provided that the UserFragment is your child fragment (a child of ContainerFragment), onActivityResult
method does not execute once you return from your activity which has been started with
startActivityForResult
.
It was a bug in the support library, I came over similar situation a while ago and it still was not fixed. Honestly, I am not sure whether it is fixed at the moment, you have to find out.
Here is a solution describing how to handle that:
http://inthecheesefactory.com/blog/how-to-fix-nested-fragment-onactivityresult-issue/en
https://gist.github.com/artem-zinnatullin/6916740
Basically the easiest way to make onActivityResult method executed in the child fragment is to start the activity from Activity level getActivity().startActivityForResult()
or Parent Fragment getParentFragment().startActivityForResult()
and notifying manually every fragment belonging to the calling Activity about invoked Activity's result.
Alternatively you can use some open source:
https://github.com/nuuneoi/StatedFragment
Hope that helps somehow.
Response to the Supplement:
Just as stated above, BaseContainerFragments
belong to MainActivity, for those fragments onActivityResult
method is called normally.
The problem begins when a child fragment is added to a parent fragment. For the child fragments onActivityResult
is not called and you have to handle it manually in the Activity or the ParentFragment.
See :