在本人博客中Android活动返回不在再支持startActivityForResult()后的处理方法已经记录采用ActivityResultLauncher来处理多活动的返回并传回数据的方式。但是采用的是布局xml+viewBinding技术。目前,谷歌官方推荐使用JetPack Compose组件来定义界面。在本文中,将介绍在JetPack Compose定义的界面中ActivityResultLauncher的实现不同活动跳转并返回数据。
例:从MainActivity跳转到OtherActivity,并从OtherActivity返回。运行界面类似:
在主活动中定义ActivityResultLauncher来处理从其他活动返回的处理。
val resultLauncher:ActivityResultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult(),
ActivityResultCallback {
if(it.resultCode== Activity.RESULT_OK){
val returnData = it.data?.getStringExtra(“returnData”)
Toast.makeText(this,returnData,Toast.LENGTH_LONG).show()
}
})
具体代码如下:
class MainActivity : ComponentActivity() {
private lateinit var resultLauncher: ActivityResultLauncher<Intent>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//注册活动结果,处理从其他活动返回的动作
resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult(),
ActivityResultCallback {
if(it.resultCode== Activity.RESULT_OK){
val returnData = it.data?.getStringExtra("returnData")
Toast.makeText(this,returnData,Toast.LENGTH_LONG).show()
}
})
setContent {
ForCourseTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
JumpOtherScreen(resultLauncher)
}
}
}
}
}
@Composable
fun JumpOtherScreen(resultLauncher: ActivityResultLauncher<Intent>) {
val context = LocalContext.current
Box(modifier = Modifier.fillMaxSize().background(Color.Green),
contentAlignment = Alignment.Center){
Button(onClick={
val intent = Intent(context,OtherActivity::class.java)
intent.putExtra("data","从MainActivity跳转到OtherActivity")
resultLauncher.launch(intent)
}){
Text("跳转到其他页面",fontSize = 30.sp,color = Color.White)
}
}
}
在其他活动中增加下列处理方式,来解决从当前活动返回上一个活动:
val intent = Intent()
intent.putExtra(“returnData”,“从OtherActivity返回”)
context.setResult(Activity.RESULT_OK,intent)
context.finish()
这里:context表示活动。
class OtherActivity : ComponentActivity() {
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val receivedData = intent.getStringExtra("data")
setContent {
ForCourseTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
DisplayScreen(receivedData)
}
}
}
}
}
@Composable
fun DisplayScreen(data:String?){
val context = LocalContext.current as OtherActivity
Box(contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize().background(Color.Blue)){
Column{
Text("OtherActivity界面接受的数据:${data!!}",fontSize = 30.sp,color= Color.White)
Button(onClick={
val intent = Intent()
intent.putExtra("returnData","从OtherActivity返回")
context.setResult(Activity.RESULT_OK,intent)
context.finish()
}){
Text("返回到MainActivity",fontSize = 30.sp,color = Color.White)
}
}
}
}