英文:
How to partially disable click on home button in Android toolbar?
问题
我已经实现了onOptionsItemSelected以控制主页按钮:
override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
        android.R.id.home -> {
            if (mode) {
                reset()
            }
        }
    }
    return super.onOptionsItemSelected(item)
}
现在,当我按下主页按钮时,我会返回到上一个片段。我需要的是,如果mode为真,当我点击主页时,仅触发reset()函数,而不返回到上一个片段。如果为假,只需返回。我该如何实现这一点?
英文:
I have implemented onOptionsItemSelected to have control over the home button:
override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
        android.R.id.home -> {
            if (mode) {
                reset()
            }
        }
    }
    return super.onOptionsItemSelected(item)
}
Now, when I press home, I go back to the previous fragment. What I need is, if the mode is true, when I click on home, to trigger ONLY the reset() function without going back to the previous fragment. If it's false, simply go back. How can I achieve this?
答案1
得分: 2
你应该返回true以告诉父级菜单项的点击已被消耗。
override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
        android.R.id.home -> {
            if (mode) {
                reset()
                return true
            }
        }
    }
    return super.onOptionsItemSelected(item)
}
英文:
You should return true to say the parent that the click on the menu item is consumed.
override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
        android.R.id.home -> {
            if (mode) {
                reset()
                return true
            }
        }
    }
    return super.onOptionsItemSelected(item)
}
</details>
				通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论