简体   繁体   中英

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. You can read about how you do that in this thread: ListSelector applies to the entire list

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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