我已经实现了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 中找到答案
- 我们需要使用
android:state_checked
而不是android:state_enabled
- 在
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_white
和 banner_green
是png。
关于android - BottomNavigationView 中的背景颜色更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41421553/