Change a specific row in the ArrayAdapter ListView of Android

I am trying to change the color in a specific line depending on different states. This is the code that 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);
 }

}

Kinda code works ... but it changes all lines. Any ideas?

+3
source share
3 answers

therefore, android reuses View every time you see that it affects all rows. You need to explicitly specify the color for each case. maybe add a “default” case to your switch statement so that it sets it according to what you default in the layout?

+3
source

mState? , , ? , getView() , . - :

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;
 }

, , reset , , 1, 2 3, switch.

, , .

+1

Found some strange things about ArrayAdapter. The method getView()gets called more than once when you add something to the adapter. It receives a call for each element in the ArrayAdapter, which is strange. This is why case-switch does not work. When he moves over the entire list, he will still be in the same state. The solution is to find your special strings, as Ben suggested. How:

if (position == 2){ //Row 3 will be red
label.setTextColor(Color.RED)
}

I find it strange, but perhaps that was how it was implemented.

-1
source

Source: https://habr.com/ru/post/1755781/


All Articles