如何从底部导航视图更改特定图标图像

8
我需要在我的Android应用程序中实现一个底部导航视图(Bottom Navigation View)。中间的图标需要是一张图片,即公司徽标。但是当我运行应用程序时,只会出现一个填充为灰色的圆形图标。上面的图片显示了我想要的效果以及我得到的结果。
我想要的: enter image description here 我得到的: enter image description here 我已经尝试了这个网站上的其他问题,但每个答案都告诉我使用XML中的drawable更改iconTintList,但中心图标是具有多个颜色的向量图。当我尝试将setIconTintList方法设置为null时,可以使中间的图标正常显示,但其他图标也会变回原始颜色。
//This doesn't work to other icons, only for the middle one 
mBottomNav.setItemIconTintList(null);

我也尝试获取菜单,并为中间的那个设置图标着色列表,就像上面的代码一样,但是也不起作用。

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    mBottomNav.getMenu().findItem(R.id.nav_buy).setIconTintList(null);
}

这是 XML 实现:
    <android.support.design.widget.BottomNavigationView
        android:id="@+id/bottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@color/kmv_background"
        app:itemIconTint="@drawable/bottom_nav_item_color"
        app:itemTextColor="@drawable/bottom_nav_item_color"
        app:labelVisibilityMode="labeled"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/bottom_navigation" />

这是Java的实现:

mBottomNav = findViewById(R.id.bottomNavigationView);
mBottomNav.setOnNavigationItemSelectedListener(this);

感谢您的帮助!
2个回答

28

我认为没有捷径可走。首先尝试使用以下方法:

   mBottomNav.setItemIconTintList(null);

那么您需要自己设计。不要忘记将按钮分开为已点击和未点击。

示例主页按钮 XML

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!--Clicked-->
    <item android:drawable="@drawable/homeclicked" android:state_checked="true" />
    <!--Not Clicked-->
    <item android:drawable="@drawable/homenotclicked" android:state_checked="false" />
</selector>

将它们添加到视图中: 示例 bottom_navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/homebuttons"
        android:icon="@drawable/homebuttonxml />

 <!--Other Buttons...-->

</menu>

最后,将视图链接到底部导航栏

<com.google.android.material.bottomnavigation.BottomNavigationView    
     android:id="@+id/bottomNavigationView"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     app:labelVisibilityMode="unlabeled"
     app:elevation="0dp"
     app:menu="@menu/bottom_navigation">  
   
</com.google.android.material.bottomnavigation.BottomNavigationView>

完美运行!非常感谢你! - Fernando Barbosa
太棒了。谢谢,这就是我在寻找的东西。 - Titus Sutio Fanpula
太棒了!非常感谢你! - Pablo DbSys
随着新版本的推出,提供了一个简短版本。 - Sambhav Khandelwal

0

对于特定的图标,可以使用以下代码:

MenuItemCompat.setIconTintMode(binding.bottomNav.menu.getItem(3), null);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接