带分隔符的CursorAdapter - 如何获得正确的游标?

时间:2013-02-13 14:45:57

标签: android android-sqlite android-cursoradapter

我正在尝试使用CursorAdapter在视图之间添加分隔符。

我知道如何添加自己的分隔符,但我不知道如何获得合适的Cursor 这样的任务。存储在CotentProvider内的所有数据都支持SQLite数据库。

分隔符存储为:_id, name

项目存储为:_id, name, ... , separator_id

到目前为止我看到的解决方案

  1. 获取所有分隔符。对于每个分隔符,独立检索项目。我认为会有很大的开销......或者我错了?
  2. item.separator_id = separator._id上加入表格,并按分隔符的某个字段对结果进行排序。然后,在CursorAdapter内查找separator_id的更改并插入分隔符视图。我觉得很乱。
  3. 有没有更好的方法来解决这个问题?

1 个答案:

答案 0 :(得分:1)

使用分隔符枚举更好。但在你的情况下

public Cursor getItemList(){
     return db.rawQuery("SELECT * FROM Items NATURAL JOIN Separators ON Item.separator_id = Separators._id");
    }

创建自定义CursorAdapter并以您的方式在bindView方法中管理它。 分隔符视图的布局应包含ImageView for separator inside。

public class MyCursorAdapter extends CursorAdapter {
      LayoutInflater inflater;
      public MyCursorAdapter(Context context, Cursor c) {
        super(context, c);
        inflater = LayoutInflater.from(context);
      }

@Override
      public void bindView(View view, Context context, Cursor cursor) {
        //cursor is already setted to requared position, just get your column
        TextView tv1 = (TextView)view.findViewById(R.id.textView1);
        TextView tv2 = (TextView)view.findViewById(R.id.textView2);
        tv1.setText(cursor.getString(1));
        tv2.setText(cursor.getString(2));
        ImageView myImageView = (ImageView)fimdViewById(R.id.my_image_view);
        if(cursor.getString(5) == "line"){
          myImageView = getResources().getIdentifier("yourpackagename:drawable/line.png");
        }else if(cursor.getString(5) == "wave"){
          myImageView = getResources().getIdentifier("yourpackagename:drawable/wave.png");
        ...
      }

  @Override
          public View newView(Context context, Cursor cursor, ViewGroup parent) {
            //here is view for each raws
            return inflater.inflate(R.layout.my_raw_view, parent, false);
          }
        }