如何使用渐变颜色为在bottomNavigationView中选择的图标着色

时间:2019-03-30 15:06:43

标签: android android-layout

我的bottomNavigationview中带有一些图标,我希望当有人选择图标时,图标的颜色更改为渐变颜色。

gradient.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="linear"
        android:startColor="#ee5f8a"
        android:endColor="#ed8f6d"
        android:angle="0"/>
</shape>

BottomNavigationview

<android.support.design.widget.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_alignParentBottom="true"
        android:background="?android:attr/windowBackground"
        app:elevation="5dp"
        app:itemIconSize="35dp"
        app:itemIconTint="@color/selector"
        app:labelVisibilityMode="unlabeled"
        app:menu="@menu/bottom_nav_menu" />

selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:color="@color/colorPrimaryDark" 
      android:state_checked="true" />
    <item android:color="#c2bdbf" />

</selector>

2 个答案:

答案 0 :(得分:0)

将此属性添加到BottomNavigationView

app:itemIconTint="@drawable/bottom_selector"

创建一个名为bottom_selector.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="#ff0000"/>
<item android:color="@color/colorPrimaryDark"/>
</selector>

答案 1 :(得分:0)

您需要可绘制的选择器而不是颜色选择器来创建渐变背景。

drawable / selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/gradient" android:state_checked="true" />
</selector>

drawable / gradient.xml(与问题相同)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="linear"
        android:startColor="#ee5f8a"
        android:endColor="#ed8f6d"
        android:angle="0"/>
</shape>

最后是您的观点

<android.support.design.widget.BottomNavigationView
    android:id="@+id/nav_view"
    android:layout_width="match_parent"
    android:layout_height="45dp"
    android:layout_alignParentBottom="true"
    android:background="?android:attr/windowBackground"
    app:elevation="5dp"
    app:itemIconSize="35dp"
    app:itemBackground="@drawable/selector"
    app:labelVisibilityMode="unlabeled"
    app:menu="@menu/bottom_nav_menu" />