Android 如何以编程方式更改底部导航视图中的特定项目背景?

Android 如何以编程方式更改底部导航视图中的特定项目背景?,android,android-activity,android-menu,bottomnavigationview,android-jetpack-navigation,Android,Android Activity,Android Menu,Bottomnavigationview,Android Jetpack Navigation,我想更改底部导航视图中最后一个选项卡的背景色。我在网上做了很多搜索,但找不到任何解决方案。我要把我所有的代码都附在这里。请找到下面的图片,这是我想要实现的 这是我的活动代码 class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentV

我想更改底部导航视图中最后一个选项卡的背景色。我在网上做了很多搜索,但找不到任何解决方案。我要把我所有的代码都附在这里。请找到下面的图片,这是我想要实现的

这是我的活动代码

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val navView: BottomNavigationView = findViewById(R.id.nav_view)

        val navController = findNavController(R.id.nav_host_fragment)
        navView.setupWithNavController(navController)
    }
}
这是我的活动xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        app:itemIconTint="@color/tab_selector"
        android:background="@drawable/shape_bottom_navigation"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>

使用以下代码更改了底部导航视图中特定选项卡的背景

var bottomNavigationMenuView = (bottomNavigationView[0] as BottomNavigationMenuView)
if (bottomNavigationMenuView.isNotEmpty()) {
    bottomNavigationMenuView[TAB_INDEX].setBackgroundResource(R.drawable.shape_refresh)
}
在我的例子中,TAB_索引是3


什么是菜单xml?我在问题中添加了菜单xml。请检查这是否回答了您的问题,然后将其标记为已接受。因此,从未回答问题队列中删除您的问题。
var bottomNavigationMenuView = (bottomNavigationView[0] as BottomNavigationMenuView)
if (bottomNavigationMenuView.isNotEmpty()) {
    bottomNavigationMenuView[TAB_INDEX].setBackgroundResource(R.drawable.shape_refresh)
}