Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent navigating to the same fragment

I'm using Android navigation jetpack library with BottomNavigationView. I have implemented the NavHost, the NavGraph and my fragments. Everything is working as intented when I use actions to navigate.

I use the following code to setup everything:

 val navController = Navigation.findNavController(this, R.id.nav_host)
 bottom_navigation.setupWithNavController(navController)

The problem is that if I click a tab 2 times the fragment is recreated twice. Is there any way to intercept navigation? I don't want to navigate to the same fragment that's being shown.

like image 683
Nacho Ramos Sánchez Avatar asked Oct 02 '19 23:10

Nacho Ramos Sánchez


2 Answers

As per this issue,

Feel free to set a OnNavigationItemReselectedListener, which takes precedence over the OnNavigationItemSelectedListener set by NavigationUI.

val navController = Navigation.findNavController(this, R.id.nav_host)
bottom_navigation.setupWithNavController(navController)
bottom_navigation.setOnNavigationItemReselectedListener {
  // Do nothing to ignore the reselection
}
like image 131
ianhanniballake Avatar answered Sep 30 '22 21:09

ianhanniballake


inside setOnItemSelectedListener use :

if( item.getItemId() == navController.getCurrentDestination().getId()){  return true; }

because OnNavigationItemSelectedListener is deprecated now.

like image 39
Mostafa Onaizan Avatar answered Sep 30 '22 20:09

Mostafa Onaizan