Reputation: 461
I need to change background color of each row on my listview .I'm using a custom listview .
each row has a RelativeLayout and I change it like this :
public View getView(int position, View convertView, ViewGroup parent) {
........
if (convertView == null) {
convertView = inflater.inflate(R.layout.item, null);
holder = new ViewHolder();
holder.rl=(RelativeLayout)convertView.findViewById(R.id.rl);
holder.rl.setBackgroundResource(R.drawable.roundcorner);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.rl.setBackgroundResource(R.drawable.round_corner_vip);
}}
I don't change every row's bakcground , I just change some of them .
I wanted to know is it a bad idea? I mean , does it consume lots of memory and it's bad for performance ?
thanks
Upvotes: 1
Views: 1008
Reputation: 12861
Yes, You can change Background Color of ListView
Row from getView()
Based on Position
.
Put this code in Your getView()
Method. i have used position % 4
for repeating color after 4th item
switch (position % 4) {
case 0:
convertView.setBackgroundColor(Color.BLACK);
break;
case 1:
convertView.setBackgroundColor(Color.RED);
break;
case 2:
convertView.setBackgroundColor(Color.GREEN);
break;
case 3:
convertView.setBackgroundColor(Color.GRAY);
break;
default:
break;
}
If You have Fix items in ListView then You can also change color according to position
if(position == 0) {
convertView.setBackgroundColor(Color.BLACK);
} else if(position == 1) {
convertView.setBackgroundColor(Color.RED);
} else if(position == 2) {
convertView.setBackgroundColor(Color.GRAY);
} else if(position == 3) {
convertView.setBackgroundColor(Color.GREEN);
}
Hope it helps!
Upvotes: 3
Reputation: 1142
Your drawable name state that you have two types of drawables roundcorner and round_corner_vip
so I think you have to set a vip flag
as @Haresh Chhelana said in the comments, then in your adapter class getView()
you should do something like that:
if(vip_flag)
{
holder.rl.setBackgroundResource(R.drawable.round_corner_vip);
}
else
{
holder.rl.setBackgroundResource(R.drawable.roundcorner);
}
// or put some more else-if conditions and set background according to conditions.
Upvotes: 3