首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android ListView 自定義 Selector 無效:缺少 android:drawSelectorOnTop="true" 導致被 Item 背景遮蓋

     編輯:程式設計綜合問答

問題現象

ListView 設置 android:listSelector="@drawable/selector",Item 布局中 getView() 設置背景色 v.setBackgroundColor(...),點擊時 Selector 不顯示。

根本原因

ListView 繪製順序:Item View 背景 → Selector Drawable → Item View 內容。
若 Item View 設置了背景(setBackgroundColor 或 XML android:background),會覆蓋 Selector。

解決方案

1. 設置 android:drawSelectorOnTop="true"(最簡單)

<ListView
    android:id="@+id/listView"
    android:listSelector="@drawable/selector"
    android:drawSelectorOnTop="true"  <!-- 關鍵屬性 -->
/>

效果:Selector 繪製在 Item View 之上(含背景),點擊/聚焦狀態可見。

2. 不給 Item 設置背景,改用 Selector 控制(正統做法)

Selector 定義各狀態背景:

<selector xmlns:android="...">
    <item android:state_pressed="true" android:drawable="@drawable/pressed_bg"/>
    <item android:state_focused="true" android:drawable="@drawable/focused_bg"/>
    <item android:drawable="@drawable/normal_bg"/> <!-- 默認背景 -->
</selector>

Item 根布局 android:background="@drawable/selector",getView() 不再 setBackgroundColor。

3. 使用 RecyclerView + ItemDecoration(現代替代)

RecyclerView 無 listSelector 概念,通過 ItemDecoration 繪制選中態,或在 Item XML 用 ?attr/selectableItemBackground:

<LinearLayout
    android:background="?android:attr/selectableItemBackground"
    android:foreground="?android:attr/selectableItemBackground" /> <!-- API 23+ foreground 更佳 -->

Selector 寫法規範

<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/colorPressed" />
    <item android:state_focused="true" android:drawable="@color/colorFocused" />
    <item android:state_selected="true" android:drawable="@color/colorSelected" />
    <item android:drawable="@color/colorNormal" /> <!-- 必須放最後作為默認 -->
</selector>

注意:state_enabled="false" 通常不用於點擊反饋。

避坑清單

  • setBackgroundColor 會覆蓋 XML android:background,Selector 失效。
  • android:cacheColorHint="#00000000" 解決滑動黑背景,與 Selector 無關。
  • 若 Item 有圖片/卡片佈局,建議用 foreground (API 23+) 代替 background 實現點擊波紋,保持圖片不變。

ListView Selector 被遮蓋是經典坑,加 drawSelectorOnTop 或移除 Item 背景改用 Selector 控制,二選一即可解決。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved