废话不多 先上结论:
app的build.gradle同时导入androidx.activity和androidx.fragment
implementation 'androidx.activity:activity:1.2.0-beta01'
implementation 'androidx.fragment:fragment:1.3.0-beta01'
registerForActivityResult是startactivityforresult的简单写法,直接可以在方法中获取activity回调,而不必重写activity的onactivityresult的方法,方便view和activity解耦。
原本照着官方文档一步步做,结果运行的时候报错IllegalArgumentException: Can only use lower 16 bits for requestCod。一直以为我是哪里漏步骤了,查了很多资料发现需要添加androidx.fragment。
附跳转普通activity写法:
registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
Intent data = result.getData();
int resultCode = result.getResultCode();
}
}).launch(new Intent(this,MainActivity.class));
registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
if (isGranted) {
} else {
}
}).launch( Manifest.permission.WRITE_EXTERNAL_STORAGE);
20230207 add
今天再去看官方文档,发现已经写明了需要引入fragment了,估计是好多人反馈报错的问题