最近学到了registerForActivityResult,简单理解一下:
1、使用registerForActivityResult为获取到的结果注册结果回调,但其本身不会启动intent跳转
2、registerForActivityResult最后会返回一个ActivityResultLauncher对象用于启动intent跳转
3、registerForActivityResult第一个参数是ActivityResultContracts,除了通用的StartActivityForResult,还有TakePicture(拍照)、RequestPermission(请求单个权限)、PickContact(从通讯录获取联系人)等预定义好的contract
4、第二个参数中的onActivityResult() 方法用于处理获取到的数据结果
深入理解参考以下两篇文章:
https://www.cnblogs.com/–here–gold–you–want/p/14841024.html
http://www.icodebang.com/article/264591文章来源:https://www.toymoban.com/news/detail-418854.html
SecondActivity的数据返回给FirstActivity,代码如下:文章来源地址https://www.toymoban.com/news/detail-418854.html
一、FirstActivity.java
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//该方法要放在onCreate里面,不能放在监听器里
ActivityResultLauncher launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode() == Activity.RESULT_OK){
Log.d("data_return", result.getData().getStringExtra("data_return"));
}
}
});
Button button1 = (Button) findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
launcher.launch(intent);//启动intent跳转
}
});
}
}
二、SecondActivity.java
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Button button2 = (Button) findViewById(R.id.button_2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.putExtra("data_return","the data of returning to FirstActivity");
setResult(RESULT_OK,intent);
finish();
}
});
}
}
到了这里,关于registerForActivityResult()方法的简单理解和使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!