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

后端 未结 8 1708
盖世英雄少女心
盖世英雄少女心 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: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();
    }
    

提交回复
热议问题