在目前的Android Studio的版本中,原来 startActivityForresult()函数 已不再支持使用
目前用于活动跳转返回数据的是通过 registerForActivityResult()函数来支持的
下面介绍其详细使用:
1. 在类内定义 ActivityResultLauncher 变量
private ActivityResultLauncher resultLauncher;
2.通过 registerForActivityResult() 函数初始化 ActivityResultLauncher 变量
这里要注意:初始化是在onCreate(),onCreateView(),onAttach()这些的重载函数中
该函数的作用主要是处理返回结果
resultLauncher=registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() { @Override public void onActivityResult(ActivityResult result) { Intent data=result.getData(); // 获取Intent int resultCode=result.getResultCode(); //获取返回码 //根据返回码是哪个来进行不同跳转活动的处理 //跳转活动较多可以单独设置一个返回码的类来收集所有的返回码,返回码需是public权限 if (resultCode == RESULT_OK){ //和之前的方法一样,通过Intent类型的data变量的一系列get函数获取数据做处理 } // 可以设置多个else if 来判断 } });
3.在跳转活动的位置声明Intent
比如点击某按钮进行跳转,则在该按钮的点击事件内声明以下部分:
Intent intent=new Intent(FirstActivity.this, SecondActivity.class); resultLauncher.launch(intent); //这里同样可以通过put等方法,向SecondActivity传递数据
4. 在SecondActivity中传递数据给FirstActivity
Intent intent=getIntent(); intent.putExtra(String数据标识符,数据); setResult(返回码比如Result_OK,intent); this.finish();//结束当前的SecondActivity活动