Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onActivityResult never called in my nested fragment

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.

like image 807
Guy Avatar asked Feb 17 '16 14:02

Guy


Video Answer


1 Answers

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();
like image 113
Luis Miguel Sierra Avatar answered Nov 14 '22 23:11

Luis Miguel Sierra