Reputation: 33
I am trying to change the color on a specific row depending on different states. This is the code i have at the moment.
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
if (row==null) {
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.doit, parent, false);
}
TextView label = (TextView) row.findViewById(R.id.mess);
label.setText(ArrayAdapter.getItem(position));
switch(mState){
case STATE1:
label.setTextColor(Color.WHITE);
break;
case STATE2:
label.setTextColor(Color.BLACK);
break;
case STATE3:
label.setTextColor(Color.YELLOW);
break;
}
return(row);
}
}
The code kinda works..but it changes all the rows. Any ideas?
Upvotes: 3
Views: 7262
Reputation: 38789
Where is mState coming from? I don't see it coming from the object so how is it going to change value? If it can't change value as getView() is called for each row then the color can't change. I'd expect something like the following:
MyItem item = getItem( position );
switch( item.getState() ) {
case STATE_1:
label.setTextColor( R.color.white );
break;
case STATE_2:
label.setTextColor( R.color.red );
break;
case STATE_3:
label.setTextColor( R.color.green );
break;
default:
label.setTextColor( R.color.black );
break;
}
Remember what Ben stated you have to reset the colors so if your row can't be in 1, 2, or 3 state you need to add a default branch to your switch statement.
It's generally good practice to get the information used to make rendering decisions from the row object.
Upvotes: 1
Reputation: 143
Found some weird things about a ArrayAdapter
. The getView()
method is getting called more than once when you add something to the adapter. It's getting called for each item in the ArrayAdapter which is weird. This is why the case-switch does not work. When it iterates through the whole list it will still be in the same state. The solution is to find your special rows like Ben suggested. Like:
if (position == 2){ //Row 3 will be red
label.setTextColor(Color.RED)
}
I find this weird, but maybe it is how they have implemented it.
Upvotes: -1
Reputation: 16534
so android reuses the View each time that's why you're seeing it affect all the rows. What you need to do is explicitly set the color for each case. perhaps add a 'default' case to your switch statement so that it sets it to whatever you're default is in the layout?
Upvotes: 3