使用数据库与RecyclerView

5 浏览
0 Comments

使用数据库与RecyclerView

目前没有默认的RecyclerView.Adapter可用。

也许在官方发布时,Google会添加它.

由于目前没有支持RecyclerView的CursorAdapter,那么我们如何使用数据库与RecyclerView?有任何建议?

admin 更改状态以发布 2023年5月23日
0
0 Comments

我的解决方案是在我的recyclerView.Adapter实现中持有一个CursorAdapter成员。然后将创建新视图和将其绑定到光标适配器的所有处理传递给这个成员,例如:

public class MyRecyclerAdapter extends Adapter {
    // Because RecyclerView.Adapter in its current form doesn't natively 
    // support cursors, we wrap a CursorAdapter that will do all the job
    // for us.
    CursorAdapter mCursorAdapter;
    Context mContext;
    public MyRecyclerAdapter(Context context, Cursor c) {
        mContext = context;
        mCursorAdapter = new CursorAdapter(mContext, c, 0) {
            @Override
            public View newView(Context context, Cursor cursor, ViewGroup parent) {
                // Inflate the view here
            }
            @Override
            public void bindView(View view, Context context, Cursor cursor) {
                // Binding operations
            }
        };
    }
    public static class ViewHolder extends RecyclerView.ViewHolder {
        View v1;
        public ViewHolder(View itemView) {
            super(itemView);
            v1 = itemView.findViewById(R.id.v1);
        }
    }
    @Override
    public int getItemCount() {
        return mCursorAdapter.getCount();
    }
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // Passing the binding operation to cursor loader
        mCursorAdapter.getCursor().moveToPosition(position); //EDITED: added this line as suggested in the comments below, thanks :)
        mCursorAdapter.bindView(holder.itemView, mContext, mCursorAdapter.getCursor());
    }
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // Passing the inflater job to the cursor-adapter
        View v = mCursorAdapter.newView(mContext, mCursorAdapter.getCursor(), parent);
        return new ViewHolder(v);
    }
}

0
0 Comments

如果你正在使用 CursorLoader 运行查询,并且想要使用 RecyclerView 而不是 ListView

你可以尝试我的 CursorRecyclerViewAdapter: CursorAdapter in RecyclerView

0