Android : ListVIew : change background onClick

10,611

Solution 1

The problem is that your adapter for list is reusing the views which are moved out of screen.

The solution is to set default color in adapter for other views

public View getView(int position, View convertView, ViewGroup parent) {

    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) convertView.getContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
         = inflater.inflate(
                R.layout.your_list_item, null);

    }
if(postion!=SelectedPosition)
  {
   convertView.setBackgroundColor(default Color);
    }
  else
   {
    convertView.setBackgroundColor(Color.argb(125,75,236,90));
   }



    return convertView;

}

Solution 2

You will have to set the background color for all your items in adapter. Set some default color to all rows and then app the color to the clicked row. But when you change color of the clicked row, make sure that the color of other rows is your default color. Then call notifydatasetchanged() from your adapter.

Share:
10,611
ilbets
Author by

ilbets

Updated on June 04, 2022

Comments

  • ilbets
    ilbets almost 2 years

    I have ListVIew , and i want to change background of items when i click on it , to show it is selected. But when I use this code (under text) it change every 13 items background color . example: if i select 1 item and scroll down it will change color of each 13 item ( 1-13-26..) . And i want to change background only for one item.

    lvpl.setOnItemClickListener( new AdapterView.OnItemClickListener() {
         @Override
         public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               TextView tv = (TextView) view
               tv.setBackgroundColor(Color.argb(125,75,236,90));
               final_ids.add(ids.get(position));
         }
    });
    
  • arshu
    arshu over 10 years
    @CVS : if the solution helped you, then please accept the answer. I really need to increase my repo.
  • Nezam
    Nezam almost 10 years
    how to get SelectedPosition here?