How to handle back button when at the starting destination of the navigation component

后端 未结 8 1679
盖世英雄少女心
盖世英雄少女心 2021-01-02 05:01

I\'ve started working with the new navigation component and I\'m really digging it! I do have one issue though - How am I supposed to handle the back button when I\'m at the

相关标签:
8条回答
  • 2021-01-02 05:37

    I had a similar scenario where I wanted to finish the activity when I was at the start destination and do a regular 'navigateUp' when I was further down the navigation graph. I solved this through a simple extension function:

    fun NavController.navigateUpOrFinish(activity: AppCompatActivity): Boolean {
    return if (navigateUp()) {
        true
    } else {
        activity.finish()
        true
    }
    

    }

    And then call it like:

    override fun onSupportNavigateUp() = 
            findNavController(R.id.nav_fragment).navigateUpOrFinish(this)
    

    However I was unable to use NavigationUI as this would hide the back arrow whenever I was at the start destination. So instead of:

    NavigationUI.setupActionBarWithNavController(this, controller)
    

    I manually controlled the home icon:

    setSupportActionBar(toolbar)
    supportActionBar?.setDisplayHomeAsUpEnabled(true)
    supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_navigation_back)
    
    0 讨论(0)
  • 2021-01-02 05:43

    Override onBackPressed in your activity and check if the current destination is the start destination or not.

    Practically it looks like this:

    @Override
    public void onBackPressed() {
        if (Navigation.findNavController(this,R.id.nav_host_fragment)
                .getCurrentDestination().getId() == R.id.your_start_destination) {
            // handle back button the way you want here
            return;
        }
        super.onBackPressed();
    }
    
    0 讨论(0)
提交回复
热议问题