Android Fragment jumps to Activity and uses startActivityForResult to get the return value

foreword

Fragment jumps to Activity and uses startActivityForResult to get the return value.
If you get it directly, you can't get the result.

Need to traverse in the activity to which the fragment belongs

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    
    
        super.onActivityResult(requestCode, resultCode, data);
        //遍历调用onActivityResult
        for (Fragment fragment : getSupportFragmentManager().getFragments()) {
    
    
            fragment.onActivityResult(requestCode, resultCode, data);
        }
    }

Then call it again in fragment

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    
    
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("TAG", "1111111111111");
    }

print result confirmation

3

Notice

There is also a very serious pit that is not mentioned here, and the startup mode of the parent Activity will affect the callback of Fragment's onActivityResult. I tested and found that when the parent Activity's startup mode is set to SingleInstance, it completely blocks the Fragment's onActivityResult callback. If it is set to SingleTask, it seems to have an impact.

For example, when the fragment starts the album and selects the picture, it can only go to the activity's onActivityResult

Guess you like

Origin blog.csdn.net/Life_s/article/details/131164260