In my case, I wanted to hide the toolbar text and the icons/titles of BottomNavigationView items in the authorization fragment, which handles the initial loading of my application. When it determines that the user is authenticated and fetches their profile from the database, I load the feed fragment, which fetches data from the database and displays it to the user. What I did was add the following method to the activity that creates the layout elements and call it from its fragments, passing in a boolean to determine visibility of the items.
public void setBottomNavigationViewItemsVisibility(boolean value) {
if (this.bottomNavigationView != null) {
this.bottomNavigationView.setVisibility(View.VISIBLE);
Menu menu = this.bottomNavigationView.getMenu();
if (value) {
int[] icons = {R.drawable.ic_event_white_24dp, R.drawable.ic_explore,
R.drawable.ic_store_white_24dp, R.drawable.ic_notifications_white_24dp};
int[] titles = {R.string.feed, R.string.explore, R.string.finder, R.string.notifications};
for (int i = 0; i < menu.size(); i++) {
menu.getItem(i).setIcon(icons[i]);
menu.getItem(i).setTitle(titles[i]);
menu.getItem(i).setEnabled(true);
}
} else {
for (int i = 0; i < menu.size(); i++) {
menu.getItem(i).setIcon(R.drawable.ic_empty);
menu.getItem(i).setTitle(R.string.title_empty);
menu.getItem(i).setEnabled(false);
}
}
}
}
We declare an array of drawable ids and an array of title ids to match what we have declared in the menu XML file. If true, we iterate through the menu items and set their icon, title, and their state to default values. If false, we set the icon to a transparent icon (removing the icon affects its size), set the toolbar title to an empty string, and disable it.
BottomNavigationView Menu:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/bottom_navigation_view_home">
<item
android:id="@+id/action_feed"
android:enabled="true"
android:icon="@drawable/ic_event_white_24dp"
android:title="@string/feed"
app:showAsAction="ifRoom" />
<item
android:id="@+id/action_explore"
android:enabled="true"
android:icon="@drawable/ic_explore"
android:title="@string/explore"
app:showAsAction="ifRoom" />
<item
android:id="@+id/action_finder"
android:enabled="true"
android:icon="@drawable/ic_store_white_24dp"
android:title="@string/finder"
app:showAsAction="ifRoom" />
<item
android:id="@+id/action_notifications"
android:enabled="true"
android:icon="@drawable/ic_notifications_white_24dp"
android:title="@string/notifications"
app:showAsAction="ifRoom" />
</menu>
Empty Icon (ic_empty.xml):
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0">
<path
android:fillColor="#00FFFFFF"
android:pathData="M8" />
</vector>
Empty Title (title_empty):
<string name="title_empty" />