有这样一个场景:需要当前Activity
启动另一个Activity
,并接收该Activity
返回数据。
为了获取被启动Activity返回的数据,需要做下面两个操作:
- 1- 当前
Activity
需要重新写onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
方法,当被启动的Activity
返回时,会触发这个方法,其中requestCode
是请求码,resultCode
是返回的 结果码。这些个都可以由业务需求来指定。 - 2- 被启动的
Activity
需要调用setResult()
设置处理结果
具体如下
当前Activity
const val REQUEST_CODE = 1019
const val RESULT_CODE = 1018
class MainActivity : Activity() {
private var showLabel:TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
showLabel = findViewById(R.id.topshowlabel)
val btn = findViewById<Button>(R.id.btnclick)
btn.setOnClickListener {
//启动指定Activity并等待返回结果,其中REQUEST_CODE是请求码,用于标识该请求
startActivityForResult(Intent(this@MainActivity,SelectedInfoActivity::class.java),REQUEST_CODE)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
//处理特定的结果
if (requestCode == REQUEST_CODE && resultCode == RESULT_CODE){
showLabel!!.text = data!!.extras.get("value").toString()
}
}
}
被启动的Activity
listview.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
val msg = "第 $position 条数据"
val intentt = intent
intentt.putExtra("value",msg)
//设置结果码 并设置借宿之后要回退的Activity
this@SelectedInfoActivity.setResult(RESULT_CODE,intentt)
this@SelectedInfoActivity.finish()
}
网友评论