Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding different menu with different fragment with Navigation component

I have an activity with BottomNavigationBar.

I show app logo in middle in toolbar by default.

Now I have to show SearchBar on entire toolbar when one of the bottomNavigation item is selected. Also, I want to revert to default toolbar view (one with logo in middle) on selecting any other bottomNavigation item.

How can i do this with Navigation component?

If I have to use ViewSwitcher or ActionMode, the whole idea of navigation component will have to be dropped as I can handle a few fragment transaction by myself.

Help me out here.

like image 227
Rahul Sharma Avatar asked Jan 28 '23 08:01

Rahul Sharma


1 Answers

There's two approaches to do this:

1) Have each Fragment implement its own Toolbar

This approach gives you the ultimate flexibility in what each Fragment is responsible for, but is more suitable if you have many different types of Fragments or need scrolling behavior that is different for each Fragment.

2) Use a OnNavigatedListener to change your Activity's Toolbar

The NavController allows you to attach any number of OnNavigatedListener instances, which give you a callback whenever the current destination / item changes.

This allows you to write code in your Activity such as:

navController.addOnNavigatedListener { navController, destination ->
  if (destination.id == R.id.search_destination) {
    // Update your Toolbar to be a SearchBar
  } else {
    // Reset it back to a standard Toolbar
  }
}
like image 54
ianhanniballake Avatar answered Jan 31 '23 09:01

ianhanniballake