onActivityResult never called in my nested fragment
Asked Answered
I

2

5

I have many nested fragments.

  • Activity A
    • MainFragment (in a FrameLayout)
      • Fragment A (in a FrameLayout in MainFragment)
      • Fragment B (in a FrameLayout in MainFragment)
        • Fragment C (in a ViewPager in Fragment B)
        • Fragment D (in a ViewPager in Fragment B) <--- this is where I want to catch onActivityResult

This is how I start activity for result:

startActivityForResult(Intent.createChooser(intent, "Title"), FILE_PICK);

I don't have onActivityResult overriden anywhere else. I tried to call it in Activity A and it got called, but then even though I called super, it never came to Fragment D. Also tried to call onActivityResult in MainFragment and it never gets called there either.

Infanticide answered 17/2, 2016 at 14:14 Comment(2)
This should be able to help you out : https://mcmap.net/q/1921892/-custom-recycleradapter-and-startactivityforresult you may find you have to call getChildFragmentManager() as its nested fragmentKlehm
blog.shamanland.com/2014/01/nested-fragments-for-result.html not sure if this is still up-to-date, or it was fixed. However this may be the case, i guess.Everglades
P
12

The event is going to be received in the activity. To have it in Fragment D you have to propagate it.

On your parent activity override onActivityResult and start calling the onActivityResult of your fragments:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    List<Fragment> fragments = fragmentManager.getFragments();
    if(fragments != null){
        for(Fragment fragment : fragments){
            fragment.onActivityResult(requestCode, resultCode, data);
        }
    }
}

In your parent fragment you have to do the same thing, but remember to use getChildFragmentManager to get the fragment manager of the fragment

    List <Fragment> fragments = getChildFragmentManager().getFragments();
Paschasia answered 17/2, 2016 at 14:21 Comment(1)
Thanks. I accepted this answer, because it is a "universal" solution to this problem. You simply call onActivityResult in all nested fragments. However I'd like to point out that @Jagu (below) also posted a very nice solution which solves this problem for a single fragment (exactly what I need).Infanticide
G
4

For calling onActivityResult on the FragmentD override onActivityResult in the parent activity like:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Fragment fragmentD = getSupportFragmentManager().findFragmentByTag("FRAGMENT_D_TAG");
        if (fragmentD != null) {
            fragmentD.onActivityResult(requestCode, resultCode, data);
        }
    }
Gerrit answered 17/2, 2016 at 14:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.