onActivityResult() not called in new nested fragment API

烂漫一生 提交于 2019-11-26 17:15:32
faylon

Yes, the onActivityResult() in nested fragment will not be invoked by this way.

The calling sequence of onActivityResult (in Android support library) is

  1. Activity.dispatchActivityResult().
  2. FragmentActivity.onActivityResult().
  3. Fragment.onActivityResult().

In the 3rd step, the fragment is found in the FragmentMananger of parent Activity. So in your example, it is the container fragment that is found to dispatch onActivityResult(), nested fragment could never receive the event.

I think you have to implement your own dispatch in ContainerFragment.onActivityResult(), find the nested fragment and invoke pass the result and data to it.

pvshnik

I solved this problem with the following code (support library is used):

In container fragment override onActivityResult in this way:

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

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

Now nested fragment will receive call to onActivityResult method.

Also, as noted Eric Brynsvold in similar question, nested fragment should start activity using it's parent fragment and not the simple startActivityForResult() call. So, in nested fragment start activity with:

getParentFragment().startActivityForResult(intent, requestCode);

Here's how I solved it.

In Activity:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    List<Fragment> frags = getSupportFragmentManager().getFragments();
    if (frags != null) {
        for (Fragment f : frags) {
            if (f != null)
                handleResult(f, requestCode, resultCode, data);
        }
    }
}

private void handleResult(Fragment frag, int requestCode, int resultCode, Intent data) {
    if (frag instanceof IHandleActivityResult) { // custom interface with no signitures
        frag.onActivityResult(requestCode, resultCode, data);
    }
    List<Fragment> frags = frag.getChildFragmentManager().getFragments();
    if (frags != null) {
        for (Fragment f : frags) {
            if (f != null)
                handleResult(f, requestCode, resultCode, data);
        }
    }
}

This problem has been fixed in Android Support Library 23.2 onwards. We don't have to do anything extra anymore with Fragment in Android Support Library 23.2+. onActivityResult() is now called in the nested Fragment as expected.

I have just tested it using the Android Support Library 23.2.1 and it works. Finally I can have cleaner code!

So, the solution is to start using the latest Android Support Library.

I have search the FragmentActivity source.I find these facts.

  1. when fragment call startActivityForResult(), it actually call his parent FragmentActivity's startAcitivityFromFragment().
  2. when fragment start activity for result,the requestCode must below 65536(16bit).
  3. in FragmentActivity's startActivityFromFragment(),it call Activity.startActivityForResult(), this function also need a requestCode,but this requestCode is not equal to the origin requestCode.
  4. actually the requestCode in FragmentActivity has two part. the higher 16bit value is (the fragment's index in FragmentManager) + 1.the lower 16bit is equal to the origin requestCode. that's why the requestCode must below 65536.

watch the code in FragmentActivity.

public void startActivityFromFragment(Fragment fragment, Intent intent,
        int requestCode) {
    if (requestCode == -1) {
        super.startActivityForResult(intent, -1);
        return;
    }
    if ((requestCode&0xffff0000) != 0) {
        throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
    }
    super.startActivityForResult(intent, ((fragment.mIndex+1)<<16) + (requestCode&0xffff));
}

when result back.FragmentActivity override the onActivityResult function,and check if the requestCode's higher 16bit is not 0,than pass the onActivityResult to his children fragment.

    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    mFragments.noteStateNotSaved();
    int index = requestCode>>16;
    if (index != 0) {
        index--;
        final int activeFragmentsCount = mFragments.getActiveFragmentsCount();
        if (activeFragmentsCount == 0 || index < 0 || index >= activeFragmentsCount) {
            Log.w(TAG, "Activity result fragment index out of range: 0x"
                    + Integer.toHexString(requestCode));
            return;
        }
        final List<Fragment> activeFragments =
                mFragments.getActiveFragments(new ArrayList<Fragment>(activeFragmentsCount));
        Fragment frag = activeFragments.get(index);
        if (frag == null) {
            Log.w(TAG, "Activity result no fragment exists for index: 0x"
                    + Integer.toHexString(requestCode));
        } else {
            frag.onActivityResult(requestCode&0xffff, resultCode, data);
        }
        return;
    }

    super.onActivityResult(requestCode, resultCode, data);
}

so that's how FragmentActivity dispatch onActivityResult event.

when your have a fragmentActivity, it contains fragment1, and fragment1 contains fragment2. So onActivityResult can only pass to fragment1.

And than I find a way to solve this problem. First create a NestedFragment extend Fragment override the startActivityForResult function.

public abstract class NestedFragment extends Fragment {

@Override
public void startActivityForResult(Intent intent, int requestCode) {

    List<Fragment> fragments = getFragmentManager().getFragments();
    int index = fragments.indexOf(this);
    if (index >= 0) {
        if (getParentFragment() != null) {
            requestCode = ((index + 1) << 8) + requestCode;
            getParentFragment().startActivityForResult(intent, requestCode);
        } else {
            super.startActivityForResult(intent, requestCode);
        }

    }
}

}

than create MyFragment extend Fragment override onActivityResult function.

public abstract class MyFragment extends Fragment {

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    int index = requestCode >> 8;
    if (index > 0) {
        //from nested fragment
        index--;

        List<Fragment> fragments = getChildFragmentManager().getFragments();
        if (fragments != null && fragments.size() > index) {
            fragments.get(index).onActivityResult(requestCode & 0x00ff, resultCode, data);
        }
    }
}

}

That's all! Usage:

  1. fragment1 extend MyFragment.
  2. fragment2 extend NestedFragment.
  3. No more different.Just call startActivityForResult() on fragment2, and override the onActivityResult() function.

Waring!!!!!!!! The requestCode must bellow 512(8bit),because we spilt the requestCode in 3 part

16bit | 8bit | 8bit

the higher 16bit Android already used,the middle 8bit is to help fragment1 find the fragment2 in his fragmentManager array.the lowest 8bit is the origin requestCode.

For Main Activity you write OnActivityForResult with Super class like as

  @Override
public void onActivityResult(int requestCode, int resultCode, Intent result) {
    super.onActivityResult(requestCode, resultCode, result);
    if (requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) {
        beginCrop(result.getData());
    } }

For activity Write intent without getActivity() like as

 Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
        pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
       startActivityForResult(pickContactIntent, 103);

OnActivityResult for fragment

   @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 101 && resultCode == getActivity().RESULT_OK && null != data) {

}}

JulianLiu

I faced the same problem! I solved it by using static ChildFragment in the ParentFragment, like this:

private static ChildFragment mChildFragment;

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    mChildFragment.onActivityResult(int requestCode, int resultCode, Intent data);

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!