开发者

How to override CursorAdapter bindView

开发者 https://www.devze.com 2023-01-27 14:57 出处:网络
I\'m trying to display information from a Cursor in a ListView, each row contains a ImageView and a TextView. I have a CustomCursorAdapter extending CursorAdapter, in bindView I evaluate the data 开发

I'm trying to display information from a Cursor in a ListView, each row contains a ImageView and a TextView. I have a CustomCursorAdapter extending CursorAdapter, in bindView I evaluate the data 开发者_JAVA百科from the cursor and based on that set the views image and text.

When I run the app the ListView displayes the correct amount of rows, but they are empty. I know I have missed something when overriding bindView, but I'm not sure what.

Any help would be greatly appreciated.

private class CustomCursorAdapter extends CursorAdapter {

  public CustomCursorAdapter() {
    super(Lmw.this, monitorsCursor);
  }

  @Override
  public View newView(Context context, Cursor cursor, ViewGroup parent) {
    LayoutInflater layoutInflater = getLayoutInflater();

    return layoutInflater.inflate(R.layout.row, null);
  }

  @Override
  public void bindView(View view, Context context, Cursor cursor) {
    try {
      int monitorNameIndex = cursor.getColumnIndexOrThrow(DbAdapter.MONITORS_COLUMN_MONITOR_NAME);
      int resultTotalResponseTimeIndex = cursor.getColumnIndexOrThrow(DbAdapter.RESULTS_COLUMN_TOTAL_RESPONSE_TIME);

      String monitorName = cursor.getString(monitorNameIndex);
      int warningThreshold = cursor.getInt(resultTotalResponseTimeIndex);

      String lbl = monitorName + "\n" + Integer.toString(warningThreshold) + " ms";

      TextView label = (TextView) view.findViewById(R.id.label);     
      label.setText(lbl);

      ImageView icon = (ImageView)view.findViewById(R.id.icon);
      if(warningThreshold < 1000) {
        icon.setImageResource(R.drawable.ok);      
      } else {
        icon.setImageResource(R.drawable.alarm);
      }


    } catch (IllegalArgumentException e) {
      // TODO: handle exception
    }
  }
}


The bindView() method seems ok.

Try replacing your newView() method:

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return mInflater.inflate(R.layout.row, parent, false);
}

And, for performance reasons:

  • move getLayoutInflater() in the constructor
  • same thing with all the cursor.getColumnIndexOrThrow() calls, as ened already said in the
    comments
  • use a StringBuilder for creating your lbl text
  • there's no need to do Integer.toString(warningThreshold)... just use warningThreshold

Later edit: The only difference between your inflate() method and the one I suggested is that this one creates layout params that match the parent.

0

精彩评论

暂无评论...
验证码 换一张
取 消