BottomNavigationView中的背景颜色更改 [英] Background color change in BottomNavigationView

查看:863
本文介绍了BottomNavigationView中的背景颜色更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了BottomNavigationView,可从新的支持库25.0.0中获得该功能.这是我的代码

I have implemented BottomNavigationView which is available from the new support library 25.0.0. Here is my code for that

<android.support.design.widget.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    app:itemBackground="@color/colorPrimary"
    app:itemIconTint="@drawable/text"
    app:itemTextColor="@drawable/text"
    app:menu="@menu/bottom_navigation_main" />

text.xml可绘制

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

使用此代码,我可以在单击菜单项时更改文本颜色,但是当我将相同的内容应用于app:itemBackground时,它显示错误<item> tag requires a 'drawable' attribute or child tag defining a drawable.

With this code I am able to change text color when menu item is clicked, but when I apply same thing to app:itemBackground it is showing error <item> tag requires a 'drawable' attribute or child tag defining a drawable.

这就是我为app:itemBackground

app:itemBackground="@drawable/text"

所以我的问题是如何更改所选菜单项的背景颜色?

So my question is how can I change the background color of the selected menu item?

推荐答案

从此

  • 我们需要使用android:state_checked而不是android:state_enabled
  • onNavigationItemSelected内,您需要使用return true而不是return false.
    1. We need to use android:state_checked instead of android:state_enabled
    2. within onNavigationItemSelected you need to use return true instead of return false.

    要设置背景,我们不能在<item>中使用android:color,我们需要使用android:drawable

    and to set background, we cannot use android:color in <item>, we need to use android:drawable

    因此,这里为app:itemTextColorapp:itemIconTint

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

    并设置app:itemBackground选择器

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

    banner_whitebanner_green是png.

    这篇关于BottomNavigationView中的背景颜色更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆