第一个Activity
// 接收第二个Activity返回的回调
private val requestDataLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK) {
val data = result.data?.getStringExtra("data")
Toast.makeText(this, data, Toast.LENGTH_LONG).show()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = FirstLayoutBinding.inflate(layoutInflater)
val button1 = binding.button1
setContentView(binding.root)
button1.setOnClickListener{
// 显示调用
val intent = Intent(this, SecondActivity::class.java)
// 传值
val data = "这就是街舞"
intent.putExtra("dd", data) // 填入数据
requestDataLauncher.launch(intent)
}
}
第二个Activity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = SecondLayoutBinding.inflate(layoutInflater)
setContentView(binding.root)
// intent.getStringExtra取值
Toast.makeText(this ,intent.getStringExtra("dd"), Toast.LENGTH_SHORT).show()
// 返回值给上一个Activity
val intent = Intent()
intent.putExtra("data", "data from SecondActivity")
setResult(RESULT_OK, intent)
binding.button2.setOnClickListener{
finish()
}
}
其它
无法直接传递对象
标签:Toast,val,kotlin,安卓,binding,intent,Activity,传递数据,data From: https://www.cnblogs.com/209jkjkjk/p/18658619