onActivityResult is not being called in Fragment

后端 未结 30 2773
忘了有多久
忘了有多久 2020-11-21 04:28

The activity hosting this fragment has its onActivityResult called when the camera activity returns.

My fragment starts an activity for a result with th

30条回答
  •  旧时难觅i
    2020-11-21 05:11

    FOR MANY NESTED FRAGMENTS (for example, when using a ViewPager in a fragment)

    In your main activity:

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

    In your fragment:

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        for (Fragment fragment : getChildFragmentManager().getFragments()) {
            fragment.onActivityResult(requestCode, resultCode, data);
        }
    }
    

    In your nested fragment

    Call activity

    getParentFragment().startActivityForResult(intent, uniqueInstanceInt);
    

    uniqueInstanceInt - replace it with an int that is unique among the nested fragments to prevent another fragment treat the answer.

    Receive response

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == uniqueInstanceInt ) {
            // TODO your code
        }
    }
    

    Attention

    A number between 0 and 65536 need be used in uniqueInstanceInt for error avoid "Can only use lower 16 bits for requestCode".

提交回复
热议问题