[英]Change the background color of a single Spinner Item in Android upon Item's Selection
[英]change background color on list item selection android
你好朋友我想在列表視圖中的列表選擇上更改列表的背景顏色(選擇時為白色),如果我選擇任何其他位置,則第一個選定的行將進入其先前狀態,當前選定的行背景變為白色。
public void onListItemClick(ListView parent, View v, int position, long id) {
super.onListItemClick(parent, v, position, id);
//do some stuff here
Toast.makeText(getApplicationContext(), "You have selected"+(position+1)+"th item", Toast.LENGTH_SHORT).show();
}
我不會在代碼中這樣做,因為您以后可能要更改顏色,並且不應該對“布局/樣式”代碼進行硬編碼。
而是創建一個樣式,並將其應用於xml中的ListView。 您可以在此線程中了解如何執行此操作: ListSelector適用於整個列表
您的列表視圖點擊監聽器:
yourlistView.setOnItemClickListener(new OnItemClickListener() {
@Override public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
yourAdapter.toggleSelected(position);
yourAdapter.notifyDataSetChanged();
}
});
然后在適配器中創建一個ArrayList
並將其初始化以存儲列表視圖項目的所有位置:
public ArrayList<Integer> selectedIds = new ArrayList<Integer>();
int length = yourmainarraylist.size();
for(int i = 0; i < length; i++){
selectedIds.add(0);
}
然后在getView
進行檢查以切換背景:
if (selectedIds.get(position)==1)
convertView.setBackgroundResource(R.drawable.list_row_selected);
else
convertView.setBackgroundResource(R.drawable.list_row);
並將此方法放入適配器
public void toggleSelected(int position) {
selectedIds.set(position, (selectedIds.get(position) == 0));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.