Android项目实战(六十六):ActivityResultContract

startActivityForResult,onActivityResult 的进阶写法

定义一个自定义ActivityResultContract

public class CommonIntentContract extends ActivityResultContract<Intent, Intent> {
    @NonNull
    @Override
    public Intent createIntent(@NonNull Context context, Intent input) {
        return input;
    }

    @Override
    public Intent parseResult(int resultCode, @Nullable Intent intent) {
        return intent;
    }
}

使用

// 开启下一页 传入Intent
launcher.launch(new Intent(this, MActivity.class)
.putExtra(StaticGather.DATA, "abc"));

// 结果回调 result为Intent
private final ActivityResultLauncher<Intent> launcher = registerForActivityResult(new CommonIntentContract(), result -> { });

 

传入参数和回调参数皆可自定义类

其他预定义Contract

 

posted @ 2023-05-16 15:16  听着music睡  阅读(205)  评论(0编辑  收藏  举报