默认情况下,菜单标题和图标显示在底部导航视图中。
我们如何以编程方式或XML隐藏/显示菜单项的标题/图标?
注意:隐藏/显示以下其中一项:“标题”或“图标”(不是全部)
答案 0 :(得分:1)
菜单:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/home"
android:icon="@drawable/home"
android:title="@string/home"/>
<item
android:id="@+id/about"
android:icon="@drawable/about" />
<item
android:id="@+id/services"
android:icon="@drawable/services" />
<item
android:id="@+id/portfolios"
android:icon="@drawable/portfolios" />
<item
android:id="@+id/contact"
android:icon="@drawable/contact" />
</menu>
方法:
private void bnvHelper(){
BottomNavigationView bnv = (BottomNavigationView)findViewById(R.id.bottom_navigation_view);
bnv.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int[] titles = {
R.string.home,
R.string.about,
R.string.services,
R.string.portfolios,
R.string.contact};
BottomNavigationView bnv = (BottomNavigationView)findViewById(R.id.bottom_navigation_view);
Menu menu = bnv.getMenu();
final int previousItem = bnv.getSelectedItemId();
final int nextItem = item.getItemId();
if (previousItem != nextItem) {
switch (nextItem) {
case R.id.home:
menu.getItem(0).setTitle(titles[0]);
menu.getItem(1).setTitle(null);
menu.getItem(2).setTitle(null);
menu.getItem(3).setTitle(null);
menu.getItem(4).setTitle(null);
break;
case R.id.about:
menu.getItem(1).setTitle(titles[1]);
menu.getItem(0).setTitle(null);
menu.getItem(2).setTitle(null);
menu.getItem(3).setTitle(null);
menu.getItem(4).setTitle(null);
break;
case R.id.services:
menu.getItem(2).setTitle(titles[2]);
menu.getItem(0).setTitle(null);
menu.getItem(1).setTitle(null);
menu.getItem(3).setTitle(null);
menu.getItem(4).setTitle(null);
break;
case R.id.portfolios:
menu.getItem(3).setTitle(titles[3]);
menu.getItem(0).setTitle(null);
menu.getItem(1).setTitle(null);
menu.getItem(2).setTitle(null);
menu.getItem(4).setTitle(null);
break;
case R.id.contact:
menu.getItem(4).setTitle(titles[4]);
menu.getItem(0).setTitle(null);
menu.getItem(1).setTitle(null);
menu.getItem(2).setTitle(null);
menu.getItem(3).setTitle(null);
break;
}
} return true;
}
});
}