ListView 包含 3 個項目,每項含兩個 TextView。初始狀態:第一項文字黑色,其餘白色。點擊其他項時,該項兩個 TextView 變黑,其他項恢復白色。
isSelected 標志位isSelected = truegetView 中根據標志位設置文字顏色isSelected 置 false,再將當前點擊項第一個 TextView 對應標志位置 true,最後調用 notifyDataSetChanged()// 在 getView 中
if (item.isSelected) {
textView1.setTextColor(Color.BLACK);
textView2.setTextColor(Color.BLACK);
} else {
textView1.setTextColor(Color.WHITE);
textView2.setTextColor(Color.WHITE);
}
// 在 OnItemClickListener 中
for (DataItem item : dataList) {
item.isSelected = false;
}
dataList.get(position).isSelected = true;
adapter.notifyDataSetChanged();
此模式通過數據驅動視圖更新,避免直接操作 View 持有引用導致的復用問題。