在MainActivity中,我这样打开一个新的Activity
val intent = Intent(context, ExerciseCatalogueActivity::class.java)
startActivityForResult(intent, REQUEST_CODE)
然后我的第二个活动中有一个clickListener调用方法
holder.itemView.setOnClickListener {
exerciseClickListener.exerciseIsClicked(currentExercise)
}
最后,我尝试将currentExercise传递给MainActivity并像这样完成第二个活动
override fun exerciseIsClicked(exercise: Exercise) {
setResult(Activity.RESULT_OK, Intent().apply{ putExtra("key", exercise) })
finish()
}
不幸的是,直到我按下返回按钮完成第二个活动之前,什么都没有发生。如果我使用onBackPressed
以编程方式进行操作,则会收到错误消息Fragment host is destroyed
答案 0 :(得分:0)
您已经像这样开始ExerciseCatalogueActivity
:
val intent = Intent(context, ExerciseCatalogueActivity::class.java)
startActivityForResult(intent, REQUEST_CODE)
现在,在第二个活动(ExerciseCatalogueActivity
)中,发送数据如下:
val result = Intent()
result.putExtra("key", exercise)
setResult(Activity.RESULT_OK, result)
finish()
然后,像这样在MainActivity
中处理结果:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
val task = data?.getStringExtra("key")
task?.let {
//Do something here with the returned value
}
}
}