android - 在 BottomNavigationView 中单独更改项目颜色

标签 android kotlin bottomnavigationview

我正在寻找一种方法来以编程方式更改 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/

相关文章:

android - 如何在按键而不是长按/点击时实现上下文菜单

android - 如何移动 Android Google Maps API 指南针位置

android - 这是创建 Realm 模块的正确方法吗?

kotlin - 结合多个流动性

android - 将 InputStream 与 MultipartEntityBuilder 一起使用 : apache error

android - LazyColumn 项目,隐式接收器无法在此上下文中调用单元

kotlin - 如何使用协程对 Kotlin-JS 代码进行单元测试?

android - 使用导航组件和底部导航时如何保存 fragment 状态?

android - 如何在没有 ActionBar 的 AndroidX 中设置 BottomNavigationView

android - 中心对齐android BottomNavigationView中的图标