我试图接收用户更改的Edit Text
值,并将该值设置为第一个活动Text View
。为此,我采用了函数onBackPressed()
和onActivityResult()
,如下所示。但是,当按下“后退”按钮时,没有数据被发送回第一个活动
第二项活动(发送回数据):
class MetaDataActivity : AppCompatActivity() {
val name by lazy {findViewById<EditText>(R.id.editTextName)}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_meta_data)
val food = intent.getParcelableExtra("Food") as Food
name.setText(food.name)
}
override fun onBackPressed() {
val intent = Intent()
intent.putExtra("New Name", name.toString())
setResult(Activity.RESULT_OK, intent)
super.onBackPressed()
}
}
第一个活动(接收用户更改的数据):
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val food1: ImageButton = findViewById(R.id.imageButtonFood1)
val name1: TextView = findViewById(R.id.textViewName1)
val date1: TextView = findViewById(R.id.textViewDate1)
val pizza = Food(
"Pizza", "www.test.com", "Italy, Tomato",
"1/1/2018", "pizza@mail.com", 5)
date1.text = pizza.date
food1.setOnClickListener()
{
val intent = Intent(this, MetaDataActivity::class.java)
intent.putExtra("Food", pizza)
startActivityForResult(intent, 1)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
val newName = data?.getStringExtra("New Name")
textViewName1.text = newName
}
}
}
我要在其中尝试从第二个活动中编辑textViewName1
的值。
我相信我的函数参数正确,只是无法确定为什么不接收用户更改的名称值?
谢谢