Search code examples
javaandroidkotlinandroid-toolbarandroid-menu

How to partially disable click on home button in Android toolbar?


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?


Solution

  • 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)
    }