Search code examples
javaandroidlistviewbaseadapter

How to change the background color of a list item at click on a button?


I have a ListView and a CustomAdapter. The elements are all successfully loaded into the list. Now I want to change the background color of a certain element of the list by clicking on an external button. But I do not know how to access a specific item in the list.

Here is the CustomAdapter class:

public class CustomAdapter extends BaseAdapter {

    private Context ctx;
    private int resource;
    private List<ItemModel> items;


    public PreorderListAdapter(Context context, int resource, List<ItemModel> items){
        this.ctx = context;
        this.resource = resource;
        this.items = items;
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public ItemModel getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @NonNull
    @Override
    public View getView(int i, View convertView, @NonNull ViewGroup parent) {

        View view = convertView;

        if(view == null){
            LayoutInflater inflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(resource, null);
        }


        TextView text1 = (TextView) view.findViewById(R.id.text1);
        TextView text2 = (TextView) view.findViewById(R.id.text2);
        TextView text3 = (TextView) view.findViewById(R.id.text3);

        ItemModel item = items.get(i);

        text1.setText(item.getName());
        text2.setText(item.getOption2());
        text3.setText(item.getOption3());

        return view;
    }
}

Solution

  • You can do it like this inside your getView() method

    view.setOnClickListener(new OnClickListener() 
       { 
         @Override
         public void onClick(View v)
             { 
               view.setBackgroundColor(ContextCompat.getColor(this, R.color.yourcolor));
              }
       });
    

    If you have a button on your view then performs the listener on that button

    If you want to get your selected item view from your parent activity then :

    yourlistview.setOnItemClickListener(new AdapterView.OnItemClickListener() 
    { 
     @Override 
      public void onItemClick(AdapterView<?>     parent,View view, int position, long id) 
        { 
           selectedposition = position ;
         }
      });
    
    
      View view = listView.getAdapter().getView(selectedposition,null,listview);
    

    Then change its background:

    view.setBackgroundColor(ContextCompat.getColor(this, R.color.yourcolor));
    

    please define your color in your color.xml file

    If you have more than one view then , create an ArrayList<View> and do some loop