Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle Toolbar back button with Navigation component

I'm following single activity approach. I have navigation toolbar, whenever i go to other screens (fragments) instead of hamburger icon i will have back arrow.

What i want to achieve is, pop my current fragment using action on pressing toolbar back arrow.

I've tried

requireActivity().getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
    @Override
    public void handleOnBackPressed() {
        NavHostFragment.findNavController(EventDetailsFragment.this)
        .navigate(R.id.action_nav_event_details_to_nav_home);
    }
});

But not getting the call over there, i checked by running app in debug mode.

like image 855
Shahal Avatar asked Oct 23 '19 06:10

Shahal


2 Answers

in Activity oncreate:

navController = findNavController(R.id.my_nav_host)
//my_nav_host defined in activity xml file as id of fragment or FragmentContainerView
val appBarConfiguration = AppBarConfiguration(navController.graph)
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration)

and:

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    if (item.itemId == android.R.id.home) {
        onBackPressed()
        return true
    }
    return true
}

then in your fragment:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val callback: OnBackPressedCallback =
        object : OnBackPressedCallback(true /* enabled by default */) {
            override fun handleOnBackPressed() {
                //do what you want here
            }
        }
    requireActivity().onBackPressedDispatcher.addCallback(this, callback)
}
like image 116
Hadi Ahmadi Avatar answered Oct 15 '22 12:10

Hadi Ahmadi


Add this code in parent activity

Add in onCreate method

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Add this method also in parent activity

 @Override
public boolean onSupportNavigateUp() {
    return super.onSupportNavigateUp();
}
like image 39
Thoriya Prahalad Avatar answered Oct 15 '22 12:10

Thoriya Prahalad