简体   繁体   English

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

[英]change background color on list item selection android

hello frnds i want to change background color (white on selection) of list on selection of list in listview and if i select any other position then first selected row comes to its previous state and currently selected rows background become white.so how to do this 你好朋友我想在列表视图中的列表选择上更改列表的背景颜色(选择时为白色),如果我选择任何其他位置,则第一个选定的行将进入其先前状态,当前选定的行背景变为白色。

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

I wouldn't do that in code, since you later on might want to change colors, and you shouldn't have "layout/styling" code hardcoded. 我不会在代码中这样做,因为您以后可能要更改颜色,并且不应该对“布局/样式”代码进行硬编码。

Do instead create a style, and apply that to the ListView in your xml. 而是创建一个样式,并将其应用于xml中的ListView。 You can read about how you do that in this thread: ListSelector applies to the entire list 您可以在此线程中了解如何执行此操作: ListSelector适用于整个列表

Your list view click listener: 您的列表视图点击监听器:

yourlistView.setOnItemClickListener(new OnItemClickListener() {                            
    @Override public void onItemClick(AdapterView<?> arg0, View arg1,
                                      int position, long arg3) {
        yourAdapter.toggleSelected(position);
        yourAdapter.notifyDataSetChanged();              
    }       
});

Then make an ArrayList in your adapter and initialize it to store all the positions of your list view items: 然后在适配器中创建一个ArrayList并将其初始化以存储列表视图项目的所有位置:

public ArrayList<Integer> selectedIds = new ArrayList<Integer>();
int length = yourmainarraylist.size();
for(int i = 0; i < length; i++){
    selectedIds.add(0);             
}

then put a check in getView to toggle the background: 然后在getView进行检查以切换背景:

if (selectedIds.get(position)==1)
    convertView.setBackgroundResource(R.drawable.list_row_selected);
else
    convertView.setBackgroundResource(R.drawable.list_row);

and put this method in your adapter 并将此方法放入适配器

public void toggleSelected(int position) {
    selectedIds.set(position, (selectedIds.get(position) == 0));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM