我正在寻找一种方法来以编程方式更改 BottomNavigationView
中的项目颜色。
我找到了如何更改图标颜色,我按如下方式操作:
fun setMenu(selected: Int) {
bottomNavigationMenu?.let {
it.menu.findItem(R.id.bottom_menu_home).icon
.setColorFilter(getMenuColor(R.id.bottom_menu_home, selected), PorterDuff.Mode.SRC_ATOP)
// more items
it.menu.findItem(R.id.bottom_menu_fidelity)?.icon
?.setColorFilter(getMenuColor(R.id.bottom_menu_fidelity, selected), PorterDuff.Mode.SRC_ATOP)
}
}
fun getMenuColor(id: Int, selected: Int): Int {
if (Singletons.restaurant.title.isBlank())
getRestaurant()
else {
if (id == selected) return (Singletons.restaurant.color)
else return ContextCompat.getColor(this, R.color.grey7E)
}
return (0)
}
现在我正在寻找如何更改标题颜色。 我正在寻找类似的东西
it.menu.findItem(R.id.bottom_menu_home).title // etc
但我找不到正确的函数来执行此操作。
这是我来自 main_bottom_menu.xml 的项目:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/bottom_menu_home"
android:enabled="true"
android:icon="@drawable/ic_home"
android:iconTint="@color/cardview_dark_background"
android:title="@string/bottom_menu_home"
android:visible="false"
app:showAsAction="ifRoom" />
<!-- 3 more items -->
<item
android:id="@+id/bottom_menu_profile"
android:enabled="true"
android:icon="@drawable/ic_profile"
android:iconTint="@color/cardview_dark_background"
android:title="@string/bottom_menu_profile"
android:visible="false"
app:showAsAction="ifRoom" />
</menu>
奇怪的是,文本颜色等于我的colorPrimary
,因此必须在某处设置它。
目标是动态设置颜色(通过 API)。
知道我的标题颜色设置在哪里吗?
最佳答案
要设置所有项目的颜色,您只需调用 setItemTextColor()
在您的 BottomNavigationView
实例上。
要单独设置它们,您可以使用SpannableString
:
val titleSpannable = SpannableString("title")
titleSpannable.setSpan(
ForegroundColorSpan(Color.parseColor("#ffffff")),
0,
titleString.length,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
bottomNavigationView.menu.findItem(R.id.your_item_id).title = titleSpannable
关于android - 在 BottomNavigationView 中单独更改项目颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49750496/