- Android startActivityForResult 默
- Android startActivityForResult
- android startActivityForResult
- RxActivityResult,一种优雅的方式实现startA
- Android -startActivityForResult分
- Android startActivityForResult用法
- Android:startActivityForResult替换
- 如何避免使用onActivityResult,以提高代码可读性
- 四大组件分析-Activity的启动流程基于android9.0
- Android 4.4以下版本onActivityResult不
减少样板代码,解耦,灵活,易测试的目的
步骤
1.在app下的build.gradle中加入依赖:
implementation 'androidx.activity:activity:1.2.0-beta01'
implementation 'androidx.fragment:fragment:1.3.0-beta01'
2. 定义协议
新建一个Contract类,继承自ActivityResultContract<I,O>,其中,I是输入的类型,O是输出的类型。需要实现2个方法,createIntent和parseResult,输入类型I作为createIntent的参数,输出类型O作为parseResult方法的返回值
static class ResultContract extends ActivityResultContract<Boolean, RecordGasGroupRequest.GasItemBean> {
@NonNull
@Override
public Intent createIntent(@NonNull Context context, Boolean input) {
Intent intent = new Intent(context, GroupAddGasActivity.class);
intent.putExtra("b", input);
return intent;
}
@Override
public RecordGasGroupRequest.GasItemBean parseResult(int resultCode, @Nullable Intent intent) {
if (resultCode == RESULT_OK) {
return (RecordGasGroupRequest.GasItemBean) intent.getSerializableExtra("GasItemBean");
}
return null;
}
}
3. 注册协议,获取启动器-ActivityResultLauncher
注册协议,使用registerForActivityResult方法,该方法由ComponentActivity或者Fragment提供,接受2个参数,第一个参数就是我们定义的Contract协议,第二个参数是一个回调ActivityResultCallback<O>,其中O就是前面Contract的输出类型
ActivityResultLauncher<Boolean> launcher = registerForActivityResult(new ResultContract(), new ActivityResultCallback<RecordGasGroupRequest.GasItemBean>() {
@Override
public void onActivityResult(RecordGasGroupRequest.GasItemBean gasItemBean) {
LogUtils.log("返回 result:" + gasItemBean);
if (gasItemBean != null) {
mScanList.add(gasItemBean);
mScanDataAdapter.notifyDataSetChanged();
}
}
});
4. 最后,调用启动器的launch方法开启界面跳转
启动方法
launcher.launch(true);
第二个界面与原来的写法一样
setResult(RESULT_OK, new Intent().putExtra("GasItemBean", gasItemBean));
finish();
用google 预定义的Contract
主要是减少了定义Contract类的书写,其他步骤一样,主要代码
//注册协议
ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
LogUtils.log("activityResultLauncher:" +result.toString() );
if (result.getResultCode()== RESULT_OK) {
List<CheckContentBean> dataList = (List<CheckContentBean>) result.getData().getSerializableExtra("data");
mCheckContentList.clear();
mCheckContentList.addAll(dataList);
StringBuilder sb = new StringBuilder();
for (CheckContentBean bean : mCheckContentList) {
sb.append(bean.getContent()).append("\n");
}
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
mGasErrorView.setText(sb);
return;
}
}
}
//启动方法
activityResultLauncher.launch(intent);
网友评论