Custom “navigate up” behavior for certain fragment using Navigation component

前端 未结 4 406
心在旅途
心在旅途 2021-02-04 01:58

I want to add custom up navigation from fragment using Navigation component

In my build.gradle(app) I use androidx.appcompat:appcompat:1.1.0-

4条回答
  •  难免孤独
    2021-02-04 02:39

    You need to call onBackPressed() from onBackPressedDispatcher property. Assuming your Toolbar is properly setup you can use the code below in your Activity.

    override fun onOptionsItemSelected(menuItem : MenuItem?) : Boolean {
        if (menuItem.getItemId() == android.R.id.home) {
            onBackPressedDispatcher.onBackPressed()
            return true // must return true to consume it here
    
        }
        return super.onOptionsItemSelected(menuItem)
    }
    

    on Fragment override

    override fun onAttach(context: Context) {
            super.onAttach(context)            
    
            //enable menu
            setHasOptionsMenu(true)
    
            requireActivity()
                    .onBackPressedDispatcher
                    .addCallback(this){
                       //true means that the callback is enabled
                        this.isEnabled = true
                        exitDialog() //dialog to conform exit
                    }
        }
    

    What this does is :

    Trigger a call to the currently added OnBackPressedCallback callbacks in reverse order in which they were added. Only if the most false from its OnBackPressedCallback#handleOnBackPressed() will any previously added callback be called.

    I am using AndroidX in my example therefore my import will look like

    import androidx.appcompat.app.AppCompatActivity.

提交回复
热议问题