Activity返回数据给上一个Activity
代码
- kotlin:
FirstReturnActivity :
class FirstReturnActivity : AppCompatActivity() {
private lateinit var firstBinding: ActivityReturndataFirstBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
firstBinding = ActivityReturndataFirstBinding.inflate(layoutInflater)
setContentView(firstBinding.root)
firstBinding.firstGotoSecond.setOnClickListener {
val intent = Intent(this, SecondReturnActivity::class.java)
startActivityForResult(intent, 1)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when(requestCode){
1->if (resultCode== RESULT_OK){
val returnedData=data?.getStringExtra("data_return")
Toast.makeText(this,returnedData,Toast.LENGTH_SHORT).show()
}
}
}
}
SecondReturnActivity:
class SecondReturnActivity: AppCompatActivity() {
private lateinit var secondBinding: ActivityReturndataSecondBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
secondBinding= ActivityReturndataSecondBinding.inflate(layoutInflater)
setContentView(secondBinding.root)
secondBinding.secondReturn.setOnClickListener {
val intent= Intent()
intent.putExtra("data_return","Hello MainActivity")
setResult(RESULT_OK,intent)
finish()
}
}
override fun onBackPressed() {
val intent=Intent()
intent.putExtra("data_return","Hello MainActivity")
setResult(RESULT_OK,intent)
finish()
}
}
- Layout:
两个布局各加一个按钮
效果: