I have Listview with which I\'m trying to display my custom Adapter.Everything works fine except when I select list item and scroll it,the items which were not selected are alre
v.setBackgroundColor(Color.parseColor("#88dfdf"));
You should not only do that but also have an ArrayList<Boolean> selectedList
in which you 'remember' if the item is selected. Then in getView you should 'inspect' that list and put the color accordingly.
if ( selectedList.get(position) )
convertView.setBackgroundColor(Color.parseColor("#88dfdf"));
else
convertView.setBackgroundColor(Color.parseColor( normal color ));
Initializing the list in the adapter class:
ArrayList<Boolean> selectedList = new ArrayList<Boolean>();
public CustomAdapter(Context context, List<Contacts> mList)
{
.........
int nr = -1;
while (++nr < mList.size() )
selectedList.add(false);
}
}
also add this to getView() function
public View getView(final int position, View convertView, ViewGroup parent)
{ ...............................
holder.contact_img.setImageBitmap(ImageHelper.getRoundedCornerBitmap(scaleBitmap, 100));
if(selectedList.get(position)== true)
{
convertView.setBackgroundColor(Color.parseColor("#88dfdf"));
}
else
{
convertView.setBackgroundColor(Color.background_light);
}
return convertView;
}
also add the following line to your onListItemClick().
protected void onListItemClick(ListView l, View v, int position, long id)
{
..................
if(mArrayAdapter.selectedList.get(position)==true)
{
v.setBackgroundColor(Color.background_light));
mArrayAdapter.selectedList.set(position,false);
}
else
{
v.setBackgroundColor(Color.parseColor("#88dfdf"));
mArrayAdapter.selectedList.set(position,true);
Toast.makeText(getApplicationContext(), "Items Pos: " + position +"and Name : "+ name, 0).show();
}
}
and also make selectedList variable to public in CustomAdapter.
Another solution, put a simple int in your Custom list View
public class CustomListView extends BaseAdapter {
private int selected = 0;
check the position in your getView
public View getView(int position, View convertView, ViewGroup parent) {
if (position == selected)
selector.setImageResource(R.drawable.selected);
else
selector.setImageResource(R.drawable.not_selected);
and finally in the clickListener of your activity or fragment, set the position with setter/getter method and notify the adapter.
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
customListViewAdapter.setSelectedPosition(position);
customListViewAdapter.notifyDataSetChanged();
}
It works like a charm for me ;)