[英]With Android 11, why does the back button and the back swipe gesture act differently with my code?
安卓 11.
我有一个活动,顶部工具栏上有一个后退按钮。 它是使用以下代码在 Base 活动上设置的:
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
}
当我的活动完成后退按钮或后退滑动手势时,将调用以下代码:
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)
}
在onBackPressed()
中onBackPressed()
将结果设置为 -1后, finish()
导致结果设置为 0。 只需添加一个if
语句来检查按下的按钮不是后退按钮就足以解决我的问题:
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// do stuff
if (item.itemId != android.R.id.home) {
finish()
}
return super.onOptionsItemSelected(item)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.