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

Android TextView 使用 Selector 實現選中狀態背景變色完整指南

     編輯:程式設計疑難解答

常見誤區

直接在 selector XML 中引用顏色資源(<item android:drawable="@color/xxx" ...>)**無法生效**,因為 selector 的 drawable 屬性期望的是 Drawable 對象,而純顏色值不是 Drawable。

正確三步走

1. 創建兩個 Shape Drawable(分別代表選中/未選中)

res/drawable/tv_selected_bg.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/bg_item_list" />
</shape>

res/drawable/tv_normal_bg.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/transparent" />
</shape>

2. 創建 Selector 引用上述 Drawable

res/drawable/selector_education.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/tv_normal_bg" android:state_selected="false" />
    <item android:drawable="@drawable/tv_selected_bg" android:state_selected="true" />
</selector>

3. TextView 設置背景並啟用點擊

<TextView
    android:id="@+id/tv5"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="本科"
    android:textColor="@color/white"
    android:paddingLeft="25dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:clickable="true"
    android:focusable="true"
    android:background="@drawable/selector_education" />

代碼控制選中狀態

textView.setOnClickListener(v -> {
    // 單選邏輯:先取消其他,再選中當前
    textView.setSelected(!textView.isSelected());
});

關鍵點總結

  • Selector 必須引用 Drawable(shape/layer/list/bitmap),不能直接引用 @color。
  • TextView 需設置 android:clickable="true" 且 android:focusable="true" 才能接收觸摸事件觸發狀態變化。
  • state_pressed 是點擊瞬間,state_selected 是持久選中態,兩者互不衝突,按需組合。

按此結構配置,TextView 選中狀態背景變色即可完美生效。

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