I am writing an app using jetpack recommended architecture, NavigationUI, and the navigation graph. So I have one main activity with a Toolbar
, a BottomNavigationView
and the NavHostFragment
.
Everything worked nicely until now: I need to change the Toolbar
to use a CollapsingToolbarLayout
and hide the BottomNavigationView
in one of my fragment.
I tried to add a navigation listener (as described here) to hide my Toolbar
and BottomNavigationView
, and in my fragment, I inflate the new Toolbar
and call setSupportActionBar()
on the main activity.
// in MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
if(destination.getId() == R.id.detailFragment){
bottomBar.setVisibility(View.GONE);
topBar.setVisibility(View.GONE);
}else{
bottomBar.setVisibility(View.VISIBLE);
topBar.setVisibility(View.VISIBLE);
}
});
// ...
}
public void changeToolbar(Toolbar toolbar){
getSupportActionBar().hide();
setSupportActionBar(toolbar);
}
// in DetailFragment.java
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// ...
navController = NavHostFragment.findNavController(this);
AppBarConfiguration.Builder builder = new Builder(
R.id.accuracyFragment,
R.id.dataFragment,
R.id.magnetFragment,
R.id.settingsFragment);
AppBarConfiguration config = builder.build();
NavigationUI.setupWithNavController(toolbarLayout, toolbar, navController);
((MainActivity)getActivity()).changeToolbar(toolbar);
// ...
}
It almost works correctly, but:
- when I navigate up or go to another fragment, the
BottomNavigationView
is not correctly displayed. It seems to be pushed down by theToolbar
. - the transition is ugly: the toolbar is visibly changing, I can see it disappearing before being changed
So the question is: is there another way to change/hide the navigation elements from the fragment? If not, should I create a new activity?