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

Android 多個 LinearLayout 單選效果:變量記錄當前選中項切換背景

     編輯:程式設計綜合問答

實現邏輯

  1. 定義成員變量 `private LinearLayout currentSelected = null;`
  2. 為每個 LinearLayout 設置 `OnClickListener`,點擊時:
ll.setOnClickListener(v -> {
    if (currentSelected != null) {
        currentSelected.setBackgroundColor(Color.WHITE); // 恢復默認
    }
    v.setBackgroundColor(Color.GREEN); // 選中高亮
    currentSelected = (LinearLayout) v;
});

進階:狀態列表選中器

定義 `res/drawable/selector_bg.xml`:

<selector xmlns:android="...">
    <item android:state_selected="true" android:drawable="@color/green" />
    <item android:drawable="@color/white" />
</selector>

佈局中 `android:background="@drawable/selector_bg"`,代碼中 `v.setSelected(true/false)` 切換狀態,無需手動設顏色。

關鍵點

  • 單選本質:記錄「上一個選中對象」,新選中時重置舊對象。
  • 使用 `state_selected` 配合 `setSelected()` 比手動設顏色更規範,支持主題切換。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved