android - 如何覆盖 CursorAdapter bindView

标签 android sqlite overriding android-cursor

我试图在 ListView 中显示来自 Cursor 的信息,每行包含一个 ImageView 和一个 TextView。我有一个 CustomCursorAdapter 扩展 CursorAdapter,在 bindView 中,我评估来自光标的数据,并根据它设置 View 图像和文本。

当我运行应用程序时,ListView 显示了正确数量的行,但它们是空的。我知道我在覆盖 bindView 时错过了一些东西,但我不确定是什么。

如有任何帮助,我们将不胜感激。

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

最佳答案

bindView() 方法似乎没问题。

尝试替换您的 newView() 方法:

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

并且,出于性能原因:

  • getLayoutInflater() 移动到 build 者
  • 与所有 cursor.getColumnIndexOrThrow() 调用相同, 正如ened
    中所说 意见
  • 使用 StringBuilder 创建您的 lbl 文本
  • 没有必要做 Integer.toString(warningThreshold)... 只需使用warningThreshold

稍后编辑: 您的 inflate() 方法与我建议的方法之间的唯一区别是,该方法创建与父级匹配的布局参数。

关于android - 如何覆盖 CursorAdapter bindView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4284242/

相关文章:

java - 如何将要同步的电子邮件 ID 传递到 android 中的创建事件日历中?

android - 如何创建一个应用程序来监控我的 android 手机访问的 ip?

android - 如何预填充 Green DAO sqlite 数据库

xcode - 我如何在 OS X 下覆盖 malloc()、calloc()、free() 等?

c++ - 如何为可覆盖方法提供默认实现?

java - 线程问题 : NullPointerException

Android - 更改高度时阴影大小不受影响

sql - 闭表 根节点 数十百万节点查询性能

SQLITE_ERROR] 使用 union all 输入不完整

c++ - 我的方法调用是如何解决的?