I'm using navigation componetns with drawer and app bar in my program.
From home fragment, it has a recyclerview, and when each item is clicked, the nav_host_fragment host another fragment with the selected itme, using the following line:
Navigation.findNavController(view).navigate(R.id.doTimedTaskFragment, args);
The problem, is, I need to ask user if they want to give up the progress they made in the new fragment (doTimedTaskFragment) if they hit the back button in app bar.
I digged Google Document and in the following link gives how I should do it. https://developer.android.com/guide/navigation/navigation-custom-back#java
public class MyFragment extends Fragment {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This callback will only be called when MyFragment is at least Started.
OnBackPressedCallback callback = new OnBackPressedCallback(true /* enabled by default */) {
@Override
public void handleOnBackPressed() {
// Handle the back button event
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
// The callback can be enabled or disabled here or in handleOnBackPressed()
}
...
}
However, handleOnBackPressed()
never gets called, and I'm suspecting the line of code I've used above to direct to the new fragment, and I can't find a way to resolve this issue.
EDIT/UPDATE:
My question was originally asking how to handle clicking Navigation component left(back) arrow click behavior, and in my case, I overrodeonOptionsItemSelected
inside the fragment and code came to be way much cleaner and better than overriding inside MainActivity
.
The OnBackPressedCallback
is called for back button on the device not the Toolbar
back button. For the toolbar back button you have to set it up with the navigation controller.
In your activity's onCreate
:
setSupportActionBar(findViewById(R.id.toolbar))
val nc = findNavController(this, R.id.nav_host_fragment)
val appBarConfiguration = AppBarConfiguration.Builder(nc.graph).build()
setupActionBarWithNavController(
this,
nc,
appBarConfiguration
)
and then:
override fun onSupportNavigateUp(): Boolean {
//Handle the toolbar back button here.
val navController = findNavController(this, R.id.nav_host_fragment)
navController.currentDestination?.let {
if (it.id == R.id.someFragment) {
//do something here
} else {
navController.popBackStack()
}
}
return super.onSupportNavigateUp()
}