Search code examples
androidkotlinnavigation

Kotlin -How to Disable/Enable the Back Button in the Navigation Bar


When the user is completing some async task like posting something I use this code below to disable the device's built in back button (I'm new to Android so I don't know the correct term).

private var disableBackButton = false // when the user presses the post button I set this to true and after the post completes I set it back to false

// added in onCreate
private fun handleBackButtonForSDK33() {

    onBackPressedDispatcher.addCallback(this, object: OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {

            if (!disableBackButton) {
                finish()
            }
        }
    })
}

The issue is this code doesn't work for the back arrow button in the navigation bar. How can I disable/enable that too?

enter image description here


Solution

  • As per Screen Shot , It looks like you haven't done much customisation to toolbar and you are using it default . In this situation you can use below mentioned code to manage back arrow click

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
            return when(item.itemId){
                android.R.id.home ->{
                    if (!disableBackButton) {
                      finish()
                    }
                    true
                }
                else->{
                    super.onOptionsItemSelected(item)
                }
            }
    
        }
    

    android.R.id.home is provided by android , not by us so we have added just condition over here