在 Android 11 中,为什么返回按钮和向后滑动手势在我的代码中表现不同?

问题描述

安卓 11。

我有一个活动,顶部工具栏上有一个后退按钮。它是使用以下代码在 Base Activity 上设置的:

fun setupToolbar(toolbarId: Int,title: String = "") 
{
    val toolbar: Toolbar = findViewById(toolbarId)
    setSupportActionBar(toolbar)

    supportActionBar?.apply {
        setdisplayShowTitleEnabled(false)
        setdisplayHomeAsUpEnabled(true)
        val textView = findViewById<TextView>(R.id.tb_global_title)
        textView.text = title
    }
}

override fun onoptionsItemSelected(item: MenuItem): Boolean {
    // handle arrow click here
    if (item.itemId == android.R.id.home) {
       onBackpressed() // Call onBackpressed in the current activity
    }
    return super.onoptionsItemSelected(item)
}

这就是我在任何活动中设置带有后退按钮的工具栏的方式:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_image_select)
    setupToolbar(R.id.tb_image_select,getString(R.string.toolbar_image_select))
    // do stuff
}

enter image description here

enter image description here

当返回按钮 OR 在我的活动中完成向后滑动手势时,将调用以下代码

override fun onBackpressed() {
    // do stuff
    setResult(Activity.RESULT_OK)
    super.onBackpressed()
}

我期待的是这段代码调用并进入 RESULT_OK 步骤:

override fun onActivityResult(requestCode: Int,resultCode: Int,data: Intent?) {
    super.onActivityResult(requestCode,resultCode,data)
    if (resultCode == Activity.RESULT_OK) {
        rv_select_image.adapter!!.notifyDataSetChanged()
    }
}

问题是代码只在滑动手势上进入 RESULT_OK (-1),而不是后退按钮 (0)。

有人知道为什么会这样吗?

解决方法

我想通了。这只是我的一个疏忽。在活动中,当在工具栏上完成任何选择时,我在这里做了一个额外的覆盖:

override fun onOptionsItemSelected(item: MenuItem): Boolean {
   // do stuff
   finish()

   return super.onOptionsItemSelected(item)
}

finish() 导致结果被设置为 0 之前它在 onBackPressed() 中被设置为 -1。只需添加一个 if 语句来检查按下的按钮不是后退按钮就足以解决我的问题:

override fun onOptionsItemSelected(item: MenuItem): Boolean {
   // do stuff
   if (item.itemId != android.R.id.home) {
       finish()
   }

   return super.onOptionsItemSelected(item)
}