如何部分禁用Android工具栏中的主页按钮点击?

huangapple go评论90阅读模式
英文:

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>



huangapple
  • 本文由 发表于 2020年7月29日 19:50:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/63152979.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定