android - BottomNavigationView 中的背景颜色更改

标签 android bottomnavigationview

我已经实现了BottomNavigationView可从新的支持库 25.0.0 中获得。这是我的代码

<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 .

这是我尝试过的 app:itemBackground

app:itemBackground="@drawable/text"

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

最佳答案

medium post 中找到答案

  1. 我们需要使用 android:state_checked而不是 android:state_enabled
  2. onNavigationItemSelected 内您需要使用 return true而不是 return false .

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

因此,当您将其设置为 app:itemTextColor 时,它看起来如何 xml 文件和 app: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。

关于android - BottomNavigationView 中的背景颜色更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41421553/

相关文章:

android - 协调器布局中带有可滚动工具栏的底部导航

android - bottomNavigationView 目的地可以水平放置而不是堆叠

Android - 新 BottomNavigationBar 中的 PageView - 防止重新加载 fragment

android - 如何解决应用启动 - 应用卡在白屏上

android - 字体等宽 Android 2.3

android - 一个列表 Activity 中的两个自定义 ListView

android - 具有左右空格问题的底部导航 View

Android OpenGL ES 2.0 纹理

android - 在 Android 2.1 中访问 .sqlite 文件

android - 使用androidx的BottomNavigationView