如上图所示:
在api29中提示已过时,官方给出的替代方案是上面第二个红框的方法registerForActivityResult
该怎么用呢 ?
先看kotlin版本的写法:
private val startActivity =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
//此处是跳转的result回调方法
if (it.data != null && it.resultCode == Activity.RESULT_OK) {
it.data?.getStringExtra(NewWordActivity.EXTRA_REPLY)?.let { reply ->
val word = Word(reply)
wordViewModel.insert(word)
}
} else {
Toast.makeText(
applicationContext,
R.string.empty_not_saved,
Toast.LENGTH_LONG
).show()
}
}
?跳转方法
val intent = Intent(this@MainActivity, NewWordActivity::class.java)
// startActivityForResult(intent, newWordActivityRequestCode)
startActivity.launch(intent)
再看下Java版本的写法完整版:
/**
* @author xiayiye5
* @date 2021/9/23 13:52
*/
public class JumpPage extends AppCompatActivity {
public void goPage() {
// startActivityForResult(intent, newWordActivityRequestCode)
ActivityResultLauncher<Intent> intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
//此处是跳转的result回调方法
if (result.getData() != null && result.getResultCode() == Activity.RESULT_OK) {
result.getData().getStringExtra(NewWordActivity.EXTRA_REPLY);
} else {
Toast.makeText(getApplicationContext(), R.string.empty_not_saved, Toast.LENGTH_LONG).show();
}
}
});
Intent intent = new Intent(JumpPage.this, NewWordActivity.class);
intentActivityResultLauncher.launch(intent);
}
}
|