Through this code there is some way to change the background color of each listview item

Asked

Viewed 91 times

2

That’s how I’m doing the listing I’d like to know if it’s possible to put each item in a different color for example 1 in white and one in 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 adapts if I have an Adapter class , some way to adapt it 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; 
}
  • 1

    No, you’ll have to implement a custom Adapter.

  • @'cause it’s like I told you...

1 answer

1

For this level of customization, it will be necessary to implement an Arrayadapter!
Here’s 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); 
  • list.setAdapter(Adapter); enter where in your code ?

  • I edited the answer, I hope I helped! Greetings

  • I tried using Adapter Adapter = new Adapter< String >(Mainactivity.this, list); list.setAdapter(Adapter); but gave error na in "< String > more specifically in String

  • try as follows: Adapter Adapter = new Adapter(Mainactivity.this, list); Excuse me!

  • Still in error

  • class is called without parameter '< String >': Adapter Adapter = new Adapter(Mainactivity.this, list);

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.