【问题标题】:How to override CursorAdapter bindView如何覆盖 CursorAdapter bindView
【发布时间】:2022-01-22 04:03:21
【问题描述】:

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

当我运行应用程序时,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
    }
  }
}

【问题讨论】:

  • 我稍后会尝试,但有 1 条评论:您应该在构造函数中执行这些 cursor.getColumnIndexOrThrow(DbAdapter.MONITORS_COLUMN_MONITOR_NAME); 调用。你呢Log.e 例外呢?

标签: android sqlite overriding android-cursor


【解决方案1】:

bindView() 方法似乎没问题。

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

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

而且,出于性能原因:

  • 将getLayoutInflater()移动到 构造函数
  • 与所有cursor.getColumnIndexOrThrow() 调用相同, 正如ened在
    中已经说过的 厘米
  • 使用 StringBuilder 创建您的 lbl 文本
  • 没有必要做 Integer.toString(warningThreshold)... 只需使用 warningThreshold

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

【讨论】:

  • 原来错误实际上是在我的 sql 中,列 'RESULTS_COLUMN_TOTAL_RESPONSE_TIME' 不在游标中。感谢您提供有关性能问题的反馈。会将您的答案标记为正确。
猜你喜欢
  • 1970-01-01
  • 2012-08-26
  • 2013-08-19
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 2012-06-05
  • 1970-01-01
相关资源
最近更新 更多