Search code examples
androidandroidxandroid-architecture-navigation

How to get Back Button in Actionbar with new Jetpack navigation


I want to have a Backbutton in the default Actionbar on an new androidx jetpack navigation App.

I follow the google navigation-getting-started to build a navigation app, but I'm missing a Backbutton in the Actionbar so I add in the OnCreate of the MainActivity:

        ActionBar actionbar = getSupportActionBar();
        NavController nc = Navigation.findNavController(mainFragment.getView());
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(nc.getGraph()).build();
        androidx.navigation.ui.NavigationUI.setupActionBarWithNavController(this,nc, appBarConfiguration); 

Now I see a Backbutton in the ActionBar if I'm not in the start main fragment, but there is no back function if I tap that button. The regular back-key works fine, but how do I get the actionbar backbutton to work.

enter image description here

Update: It is not working from second fragment to first(main/root) fragment. from third to second fragment it is working. nav-graph


Solution

  • try this :-

    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //do your stuff here
                }
            });
    

    second option is;-

    @Override
        public boolean onSupportNavigateUp() {
            return super.onSupportNavigateUp();
            // do your stuff here
        }