Through this code is there any way to change the background color of each listView item

2

This is how I am doing the listing I would like to know if it is possible to put each item with a different color for example 1 to white and another to black

ArrayAdapter adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, list);


 lista.setAdapter(adapter); 

I saw this example but it only fits if I have a class adapter, any way I can adapt this to the code I showed above?

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

/* remainder is unchanged */ 

convertView.setBackgroundColor(position % 2 == 0 ? Color.WHITE : Color.GREY); 
return convertView; 
}
    
asked by anonymous 13.07.2015 / 16:07

1 answer

1

For this level of customization, you will need to implement an ArrayAdapter! Home Here is an example, this is a new class:

class Adapter extends ArrayAdapter<String>  {

        private final LayoutInflater inflater; 
        public Adapter(Context context, final List<String> list) {
            super(context, android.R.layout.simple_list_item_1, list);
            this.inflater = LayoutInflater.from(context);

        } 
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
             String item = getItem(position);
            if(convertView == null){
                convertView = inflater.inflate(android.R.layout.simple_list_item_1, null);

            }

            TextView.class.cast(convertView.findViewById(android.R.id.text1)).setText(item);
            convertView.setBackgroundColor(position % 2 == 0 ? Color.WHITE : Color.GREY);
            return convertView;
        }
    }

To use, follow:

Adapter adapter = new Adapter(MainActivity.this, list);
 lista.setAdapter(adapter); 
    
13.07.2015 / 16:45