我试图在 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/