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

Android LinearLayout 子視圖點擊切換背景色:單選狀態管理實現

     編輯:程式設計疑難解答

需求

LinearLayout 內多個子視圖,點擊某項背景變色並保持,再次點擊其他項時前一項恢復,當前項高亮——典型單選交互。

核心邏輯

  1. 維護 int selectedPosition = -1 記錄當前選中索引。
  2. 遍歷子視圖綁定 OnClickListener,tag 存索引。
  3. 點擊時:selectedPosition == tag ? 取消 : 更新 selectedPosition 並刷新所有子視圖背景。

完整代碼

LinearLayout container = findViewById(R.id.container);
int selectedPos = -1;
int normalColor = Color.WHITE;
int pressedColor = Color.parseColor("#E0F7FA");

for (int i = 0; i < container.getChildCount(); i++) {
    View child = container.getChildAt(i);
    child.setTag(i);
    child.setOnClickListener(v -> {
        int pos = (int) v.getTag();
        if (pos == selectedPos) {
            // 可選:再次點擊取消選中
            selectedPos = -1;
        } else {
            selectedPos = pos;
        }
        refreshBackgrounds();
    });
}

void refreshBackgrounds() {
    for (int i = 0; i < container.getChildCount(); i++) {
        View child = container.getChildAt(i);
        child.setBackgroundColor(i == selectedPos ? pressedColor : normalColor);
    }
}

進階:使用 Selector Drawable 替代代碼設置顏色

<!-- res/drawable/item_bg_selector.xml -->
<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:drawable="@color/pressedColor"/>
    <item android:drawable="@color/normalColor"/>
</selector>
child.setBackgroundResource(R.drawable.item_bg_selector);
child.setSelected(i == selectedPos); // 在 refreshBackgrounds 中調用

RecyclerView 替代方案

若列表動態增減、項目類型多、需動畫,**強烈建議改用 RecyclerView + Adapter**,在 onBindViewHolder 根據 selectedPos 設置 itemView.setActivated(pos == selectedPos),配合 selector 實現更優雅、可復用。

LinearLayout 手動管理適用於極簡靜態列表,複雜場景請拥抱 RecyclerView。

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