Is it possible to make CursorAdapter be set in rec

2019-03-09 20:19发布

I didn't google out a solution till now to replace listview in my project, because I need to use the cursor linked with the sqlite.

Old way as followed: listview.setAdapter(cursorAdapter) in this way, I can get the cursor to deal with data in database

but now, recycleview.setAdapter(recycleview.adapter) it doesn't recognize the adapter extending BaseAdapter

so anyone can give me a hand?

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-03-09 21:01

The new RecyclerView works with a new RecyclerView.Adapter base class. So it doesn't work with the CursorAdapter.

Currently there is no default implementation of RecyclerView.Adapter available.

May be with the official release, Google will add it.

查看更多
手持菜刀,她持情操
3楼-- · 2019-03-09 21:10

Implementing it yourself is actually quite simple:

public class CursorAdapter extends RecyclerView.Adapter<ViewHolder>{

    Cursor dataCursor;

    @Override
    public int getItemCount() {
        return (dataCursor == null) ? 0 : dataCursor.getCount();
    }


    public void changeCursor(Cursor cursor) {
        Cursor old = swapCursor(cursor);
        if (old != null) {
          old.close();
        }
      }

     public Cursor swapCursor(Cursor cursor) {
        if (dataCursor == cursor) {
          return null;
        }
        Cursor oldCursor = dataCursor;
        this.dataCursor = cursor;
        if (cursor != null) {
          this.notifyDataSetChanged();
        }
        return oldCursor;
      }

    private Object getItem(int position) {
        dataCursor.moveToPosition(position);
        // Load data from dataCursor and return it...
      }

}
查看更多
登录 后发表回答