onActivityResult遍历所有fragment

场景是,一个activity有多个fragment,每个fragment有viewpager,每个viewpager又是多个fragemnt。总之就是多重嵌套fragment。然后activity的onActivityResult需要交给fragment处理。

Step1 写个抽象的activity

/**
 * onActivityResult()时遍历所有fragment,调用handleResult()
 */
public abstract class VIPLectureFragmentActivity extends BaseActivity {

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        FragmentManager fragmentManager = getSupportFragmentManager();
        for (Fragment fragment : fragmentManager.getFragments()) {
            processAllFragment(fragment, requestCode, resultCode, data);
        }
    }

    // 遍历所有fragment
    private void processAllFragment(Fragment fragment, int requestCode, int resultCode, @Nullable Intent data) {
        if (fragment == null) {
            return;
        }
        for (Fragment childFragment : fragment.getChildFragmentManager().getFragments()) {
            processAllFragment(childFragment, requestCode, resultCode, data);
        }
        handleResult(fragment, requestCode, resultCode, data);
    }

    protected abstract void handleResult(Fragment fragment, int requestCode, int resultCode, @Nullable Intent data);
}

Step2 继承上面的activity,实现handleResult即可

@Override
    protected void handleResult(Fragment fragment, int requestCode, int resultCode, @Nullable Intent data) {
        if (!fragment.isAdded() || fragment.isDetached()) {
            return;
        }
        fragment.onActivityResult(requestCode, resultCode, data);
    }

你可能感兴趣的:(onActivityResult遍历所有fragment)