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

后端 未结 8 1677
盖世英雄少女心
盖世英雄少女心 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:34

    /** in your activity **/
    private boolean doubleBackToExitPressedOnce = false;
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onBackPressed() {
                int start = Navigation.findNavController(this, R.id.nav_host_fragment).getCurrentDestination().getId();
                if (start == R.id.nav_home) {
                    if (doubleBackToExitPressedOnce) {
                        super.onBackPressed();
                        return;
                    }
                    this.doubleBackToExitPressedOnce = true;
                    Toast.makeText(MainActivity.this, "Press back again to exits", Toast.LENGTH_SHORT).show();
    
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            doubleBackToExitPressedOnce = false;
                        }
                    }, 2000);
                } else {
                    super.onBackPressed();
                }
            }
    

提交回复
热议问题