更改列表项选择android的背景颜色

时间:2011-07-25 14:31:43

标签: android

hello frnds我想在列表视图中选择列表时更改列表的背景颜色(选择时为白色),如果我选择任何其他位置,则第一个选定的行将进入其先前状态,当前选定的行背景将变为白色。所以如何这样做

 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();
 }

2 个答案:

答案 0 :(得分:2)

我不会在代码中这样做,因为您以后可能想要更改颜色,并且您不应该使用硬编码的“布局/样式”代码。

而是创建一个样式,并将其应用于xml中的ListView。您可以在此主题中了解如何执行此操作: ListSelector applies to the entire list

答案 1 :(得分:1)

您的列表视图点击监听器:

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));
}