startActivityForResult替代⽅案startActivityForResult过时
替代⽅案:ActivityResultContract
1、如何使⽤
1.1 定义ActivityResultContract
//泛型 1-ActivityResultLauncher.launch调⽤时需要的参数类型
//泛型 2-回调ActivityResultCallback返回类型
val activityResultContract = object : ActivityResultContract<Intent, ActivityResult>() {
override fun createIntent(context: Context, input: Intent): Intent {
return input
}
override fun parseResult(resultCode: Int, intent: Intent?): ActivityResult {
return ActivityResult(resultCode,intent)
register for}
}
1.2 定义ActivityResultCallback
//页⾯返回回调
val activityResultCallback = object : ActivityResultCallback<ActivityResult> {
override fun onActivityResult(result: ActivityResult?) {
if (result != null && sultCode == RESULT_OK) {
//todo
}
}
}
1.3 activity或者fragment中进⾏注册
//参数 ActivityResultContract ActivityResultCallback
//返回值 ActivityResultLauncher
registerForActivityResult = registerForActivityResult(activityResultContract, activityResultCallback)
1.4 ActivityResultLauncher合适时机调⽤
//调⽤
registerForActivityResult?.launch(Intent(this,DetainmentActivityActivity::class.java))
2、预置实现
2.1 调⽤
val registerForActivityResult=registerForActivityResult(ActivityResultContracts.StartActivityForResult()
,object : ActivityResultCallback<ActivityResult> { override fun onActivityResult(result: ActivityResult?) {
if (result != null && sultCode == RESULT_OK) {
finish()
}
}
})
registerForActivityResult.launch(Intent(this,DetainmentActivityActivity::class.java))
2.2 StartActivityForResult代码
public static final class StartActivityForResult
extends ActivityResultContract<Intent, ActivityResult> {
@NonNull
@Override
public Intent createIntent(@NonNull Context context, @NonNull Intent input) { return input;
}
@NonNull
@Override
public ActivityResult parseResult(
int resultCode, @Nullable Intent intent) {
return new ActivityResult(resultCode, intent);
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论