簡體   English   中英

Android-更改NavigationView中單個項目的背景顏色

[英]Android - Change the background color of a single item in the NavigationView

我的應用程序具有標准的Android,外觀,導航視圖,我想知道是否可以更改列表中第一個元素的背景顏色。

我試圖通過獲取標題字符串並設置BackgroundColorSpan來做到這一點,但它只會更改TextView背景色。

val proItem = nav_view.menu.findItem(R.id.pro_item)
        val spanString = SpannableString(proItem.title)
        spanString.setSpan(BackgroundColorSpan(R.color.colorAccent), 0, spanString.length, 0)
        proItem.title = spanString

我一直在尋找與NavigationView中的app:itemBackground標記類似的東西,但是它只對列表中的每個項目都適用,而我只希望對一個項目執行。

有辦法實現嗎?

app:itemBackground可用於更改背景顏色。 您可以為選中狀態創建選擇器,並在xml中引用該選擇器。

選擇器.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- focused -->
    <item android:state_checked="true" android:drawable="@color/btn_color_green_alpha"></item>
</selector>

colors.xml

<color name="btn_color_green_alpha">#3300ff00</color>

布局文件

<android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:itemBackground="@drawable/selector"   //line to be added
        app:headerLayout="@layout/nav_header_main2"
        app:menu="@menu/activity_main2_drawer" />

希望這可以幫助。

如果您只希望選擇一種顏色的商品,而又不想將其應用於其他商品,則可以將其他商品設置為checkable = false。

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">

    <group android:checkableBehavior="single">
    <item
        android:id="@+id/nav_camera"
        android:icon="@drawable/ic_menu_camera"
        android:title="Import" />
    <item
        android:id="@+id/nav_gallery"
        android:checkable="false"                  //line added here
        android:icon="@drawable/ic_menu_gallery"
        android:title="Gallery" />
    <item
        android:id="@+id/nav_slideshow"
        android:icon="@drawable/ic_menu_slideshow"
        android:title="Slideshow" />
    <item
        android:id="@+id/nav_manage"
        android:icon="@drawable/ic_menu_manage"
        android:title="Tools" />
    </group>
</menu>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM