Reputation: 516
Is it possible to set different colors for different rows in (dynamic) ListView?
I know that I can set background colors e.g. on item click event listener, but I wonder is there a way to set colors dynamically while adding items to adapter?
itemAdapter = new ArrayAdapter<Bundle>(this, android.R.layout.simple_list_item_1, itemArray) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
LayoutInflater inflater = (LayoutInflater)getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
if (null == convertView) {
row = inflater.inflate(android.R.layout.simple_list_item_1, null);
} else {
row = convertView;
}
row.setBackgroundColor(getItem(position).getInt("color"));
TextView tv = (TextView) row.findViewById(android.R.id.text1);
tv.setText(getItem(position).getString("text"));
return row;
}
};
Upvotes: 0
Views: 185
Reputation: 134714
You'll have to write your own custom ListAdapter. You can simply extend ArrayAdapter if your data is an array or an ArrayList, and override the getView()
method. There are an abundance of answers on writing the getView()
implementation, but the basic answer for your particular question is that you'll want to add some logic:
public View getView(int pos, View convertView, ViewGroup parent) {
//do initialization work with the convertView
if(/*some logic determining whether the view should be colored*/) {
convertView.setBackgroundColor(myColor);
} else convertView.setBackgroundColor(defaultColor);
}
The important thing to remember is to set it back to the other color if it doesn't meet the logic criteria, as the views are recycled and reused, and may be in an unexpected state otherwise.
Upvotes: 2