android – 如何覆盖CursorAdapter bindView

前端之家收集整理的这篇文章主要介绍了android – 如何覆盖CursorAdapter bindView前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

任何帮助将不胜感激.

  1. private class CustomCursorAdapter extends CursorAdapter {
  2. public CustomCursorAdapter() {
  3. super(Lmw.this,monitorsCursor);
  4. }
  5. @Override
  6. public View newView(Context context,Cursor cursor,ViewGroup parent) {
  7. LayoutInflater layoutInflater = getLayoutInflater();
  8. return layoutInflater.inflate(R.layout.row,null);
  9. }
  10. @Override
  11. public void bindView(View view,Context context,Cursor cursor) {
  12. try {
  13. int monitorNameIndex = cursor.getColumnIndexOrThrow(DbAdapter.MONITORS_COLUMN_MONITOR_NAME);
  14. int resultTotalResponseTimeIndex = cursor.getColumnIndexOrThrow(DbAdapter.RESULTS_COLUMN_TOTAL_RESPONSE_TIME);
  15. String monitorName = cursor.getString(monitorNameIndex);
  16. int warningThreshold = cursor.getInt(resultTotalResponseTimeIndex);
  17. String lbl = monitorName + "\n" + Integer.toString(warningThreshold) + " ms";
  18. TextView label = (TextView) view.findViewById(R.id.label);
  19. label.setText(lbl);
  20. ImageView icon = (ImageView)view.findViewById(R.id.icon);
  21. if(warningThreshold < 1000) {
  22. icon.setImageResource(R.drawable.ok);
  23. } else {
  24. icon.setImageResource(R.drawable.alarm);
  25. }
  26. } catch (IllegalArgumentException e) {
  27. // TODO: handle exception
  28. }
  29. }
  30. }
最佳答案
bindView()方法似乎没问题.

尝试替换newView()方法

  1. @Override
  2. public View newView(Context context,ViewGroup parent) {
  3. return mInflater.inflate(R.layout.row,parent,false);
  4. }

并且,出于性能原因:

>在中移动getLayoutInflater()
构造函数
>与所有cursor.getColumnIndexOrThrow()调用相同,
已经说过了
评论
>使用StringBuilder创建lbl文本
>没有必要做Integer.toString(warningThreshold)……
只需使用warningThreshold

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

猜你在找的Android相关文章