我一直在努力实现点击时菜单颜色变化的底部导航

I have been working to achieve bottom navigation with color change in menu when clicked

尝试在单击按钮导航项时实现菜单颜色变化。

这是我的xml代码

<com.google.android.material.bottomnavigation.BottomNavigationView
        app:layout_constraintBottom_toBottomOf="parent"
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:elevation="@dimen/_10sdp"
        android:background="@color/white"
        app:menu="@menu/bottom_menu"
        app:itemTextColor="@color/button_navigation"
        app:itemIconTint="@color/button_navigation">
    </com.google.android.material.bottomnavigation.BottomNavigationView>

这是我的 activity 代码

viewBinding.navigation.setOnNavigationItemSelectedListener { item ->
        when (item.itemId) {

            R.id.homeBottom->{
                addFragment(HomeFragment(),false)

            }
            R.id.notificationBottom->{

            }
            R.id.messageBottom->{

            }
            R.id.accountBottom -> {
                addFragment(UserProfileFragment(), false)
            }
        }
        false
    }

任何建议将不胜感激。谢谢

问题就在这里

viewBinding.navigation.setOnNavigationItemSelectedListener { item ->
        when (item.itemId) {
         ...
        }
        false
    }

使用true代替flase

boolean true to display the item as the selected item and false if the item should not be selected. Consider setting non-selectable items as disabled preemptively to make them appear non-interactive.

根据您的问题,这里有两种方法:

1.) 如果你想在点击图标时设置默认 'colorPrimary' 那么只需替换 return true 而不是 setOnNavigationItemSelectedListener

并从 XML

中删除两行
app:itemTextColor="@color/button_navigation"
app:itemIconTint="@color/button_navigation"

2.) 对于不同的颜色,您必须创建一个 选择器颜色 文件。所以 在 res 中创建一个目录 color 并制作一个 navigation_color.xml 文件 喜欢:

res/color/navigation_color.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:color="@color/pink" />
    <item android:state_checked="false" android:color="@color/grey_app"/>
</selector>

并将其用于 BottomNavigationView

<com.google.android.material.bottomnavigation.BottomNavigationView
        app:layout_constraintBottom_toBottomOf="parent"
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:elevation="@dimen/_10sdp"
        android:background="@color/white"
        app:menu="@menu/bottom_menu"
        app:itemIconTint="@color/navigation_color"
        app:itemTextColor="@color/navigation_color">
    </com.google.android.material.bottomnavigation.BottomNavigationView>