LinearLayout 內多個子視圖,點擊某項背景變色並保持,再次點擊其他項時前一項恢復,當前項高亮——典型單選交互。
int selectedPosition = -1 記錄當前選中索引。OnClickListener,tag 存索引。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);
}
}
<!-- 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 + Adapter**,在 onBindViewHolder 根據 selectedPos 設置 itemView.setActivated(pos == selectedPos),配合 selector 實現更優雅、可復用。
LinearLayout 手動管理適用於極簡靜態列表,複雜場景請拥抱 RecyclerView。