Цвет строки списка активности Android в зависимости от состояния объекта

1

У меня есть ListActivity, отображающая кучу объектов из списка. Я хочу изменить цвет фона и текста строки на основе состояния двух булевых элементов в MonitorObject.

Нужно ли расширять ArrayAdapter? Если это так, образец кода будет оценен по достоинству, поскольку я пытался понять его в течение нескольких дней без успеха.

public class Lwm extends ListActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list);
    setListAdapter(new ArrayAdapter<MonitorObject>(this, R.layout.row, getMonitorObjects()));
  }

  private List<MonitorObject> getMonitorObjects() {
    List<MonitorObject> mos = new ArrayList<MonitorObject>();
    mos.add(new MonitorObject(15000, 20000, 25000));
    mos.add(new MonitorObject(15000, 14000, 18000));
    mos.add(new MonitorObject(15000, 12000, 14000));
    mos.add(new MonitorObject(100, 200, 250));
    mos.add(new MonitorObject(3000, 2500, 3500));
    return mos;
  }
}

public class MonitorObject {
  private int mTimeTotal;
  private int mWarningThreshold;
  private int mAlarmThreshold;`enter code here`
  private boolean mWarning;
  private boolean mAlarm;

  public MonitorObject(int timeTotal, int warningThreshold, int alarmThreshold) {
    this.mTimeTotal = timeTotal;
    this.mWarningThreshold = warningThreshold;
    this.mAlarmThreshold = alarmThreshold;  
    mWarning = (mTimeTotal > mWarningThreshold) ? true : false;
    mAlarm = (mTimeTotal > mAlarmThreshold) ? true : false;
  }
  /*getters, setters, tostring goes here*/
}
Теги:
listview
android-arrayadapter

1 ответ

3
Лучший ответ

Я нашел отличный учебник о том, как это сделать в бесплатной выдержке для "Руководства Занятого кодера для разработки Android" на commonsware.com. Также проверьте Google I/O 2010 - мир ListView на youtube, он содержит много полезной информации.

В основном, что мне нужно было сделать, чтобы создать настраиваемый ArrayAdapter и переопределить getView(). Выполните приведенный ниже код.

public class Lwm extends ListActivity {
  private TextView mSelection;
  private List<MonitorObject> mMonitorObjects;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mMonitorObjects = getMonitorObjects();
    setContentView(R.layout.main);
    setListAdapter(new CustomAdapter());
    mSelection = (TextView)findViewById(R.id.selection);
  }

  @Override
  public void onListItemClick(ListView parent, View v, int position, long id){
    mSelection.setText("Selection length is: " + mMonitorObjects.get(position).toString().length());
  }

  private class CustomAdapter extends ArrayAdapter<MonitorObject> {
    CustomAdapter() {
      super(Lwm.this, R.layout.row, R.id.label, mMonitorObjects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {     
      View row = convertView;

      if (row == null) {
        // This gives us a View object back which, in reality, is our LinearLayout with 
        // an ImageView and a TextView, just as R.layout.row specifies.
        LayoutInflater inflater = getLayoutInflater();      
        row = inflater.inflate(R.layout.row, parent, false);
      }

      TextView label = (TextView) row.findViewById(R.id.label);
      label.setText(mMonitorObjects.get(position).toString());
      ImageView icon = (ImageView)row.findViewById(R.id.icon);

      MonitorObject mo = getMonitorObjects().get(position);

      if (mo.ismAlarm()) {
        icon.setImageResource(R.drawable.alarm);
        row.setBackgroundColor(Color.RED);
      } else if (mo.ismWarning()){
        icon.setImageResource(R.drawable.warning);
        row.setBackgroundColor(Color.YELLOW);
      } else {
        icon.setImageResource(R.drawable.ok);
        row.setBackgroundColor(Color.GREEN);
      }

      return row;       
    }
  }

  private List<MonitorObject> getMonitorObjects() {
    List<MonitorObject> mos = new ArrayList<MonitorObject>();
    mos.add(new MonitorObject(15000, 20000, 25000));
    mos.add(new MonitorObject(15000, 14000, 18000));
    mos.add(new MonitorObject(15000, 12000, 14000));
    mos.add(new MonitorObject(100, 200, 250));
    mos.add(new MonitorObject(3000, 2500, 3500));
    return mos;
  }
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню