根据光标结果更改listview项目的背景颜色

时间:2015-07-08 13:25:13

标签: android listview simplecursoradapter custom-lists

我有以下ListView ..

private void populateKPIListView(String storedStaffId, View view, String id){
    //List 1
    Cursor cursor = db.getAllRows("*", dbTables.TABLE_KPIS, "WHERE projectid=" + id);

    int count = db.getRowCount("*", dbTables.TABLE_KPIS, "WHERE projectid=" + id);

    TextView empty = (TextView)view.findViewById(android.R.id.empty);
    if(count > 0){
        empty.setVisibility(View.GONE);
        String[] fromFieldNames = new String[] {dbTables.KEY_KPIHEADER, dbTables.KEY_TARGET, dbTables.KEY_ACTUAL};
        int[] toViewIDs  = new int[] {          R.id.card_title,        R.id.card_target,    R.id.card_actual};
        myCustomAdaptor = new CustomListAdapter(getActivity(), R.layout.kpi_list_item_card, cursor, fromFieldNames, toViewIDs, 0);
        kpiList = (ListView)view.findViewById(android.R.id.list);
        kpiList.setAdapter(myCustomAdaptor);

        kpiList.setOnItemClickListener(new OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent i = new Intent(getActivity(), KpiPopUpActivity.class);
                 i.putExtra("DB_ID", id);
                 startActivity(i);

            }

        });
    }else{
        empty.setVisibility(View.VISIBLE);
        empty.setText(R.string.kpi_empty_string);
    }
}

我需要做的是更改单个列表项的颜色,如果&#39; target&#39;低于实际的&#39;在光标中。我创建了一个简单的自定义列表适配器...

public class CustomListAdapter extends SimpleCursorAdapter {

private int mSelectedPosition;
Cursor items;
private Context context;
private int layout;

public CustomListAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int num) {
    super(context, layout, c, from, to, num);
    this.context = context;
    this.layout = layout;
} 

@Override
public View getView(int position, View convertView, ViewGroup parent) {
     View v = super.getView(position, convertView, parent);
     Cursor c = getCursor();
     c.moveToPosition(position);
     int target = c.getColumnIndex(dbTables.KEY_TARGET);
     int actual = c.getColumnIndex(dbTables.KEY_ACTUAL);
     RelativeLayout relLay = (RelativeLayout)v.findViewById(R.id.kpi_box);
     Log.i(""+target, actual+"");
     if (actual > target) {
         // Set the background color of the text.

         relLay.setBackgroundColor(v.getResources().getColor(R.color.urgent));
     } else {
         relLay.setBackgroundColor(v.getResources().getColor(R.color.white));
     }
     return v;
  }

}

问题是这会将所有列表项更改为红色。 Log生成相同的结果会为每个项目产生相同的结果(因此它们都是红色的)。我说每个项目的目标都是7,实际值是8.实际上我知道没有任何结果具有这些数字的实际或目标。

1 个答案:

答案 0 :(得分:2)

问题是,您获取列索引而不是该行列中的值。请尝试以下方法:

int target = c.getInt(c.getColumnIndex(dbTables.KEY_TARGET));
int actual = c.getInt(c.getColumnIndex(dbTables.KEY_ACTUAL));