使用光标适配器实现回收器视图



如何使用光标实现回收器视图。我尝试实现此代码,但是此代码使用一些类来存储每一行,但我不想为了存储游标的每一行而创建一些类。我还发现了这篇文章,其中说我们在使用光标时不需要创建类。我很困惑使用哪种方法以及如何使用它。我试图实现stackOverFlow上存在的大部分代码,但它们几乎都是一样的。

我也用这个尝试了我的代码:

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder>{
private Cursor cursor;
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView title,text;
CardView cd;
LinearLayout ll;
public MyViewHolder(View v){
super(v);
title = v.findViewById(R.id.childTitleView);
text = v.findViewById(R.id.childTextView);
cd = v.findViewById(R.id.parentCardView);
ll = v.findViewById(R.id.ll);
}
}
public RecyclerViewAdapter(Cursor c){
this.cursor = c;
}
@Override
public int getItemCount() {
return cursor.getCount();
}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
cursor.moveToNext();
String t = cursor.getString(cursor.getColumnIndex(RecordContract.RecordEntry.COLUMN_TITLE));
String d = cursor.getString(cursor.getColumnIndex(RecordContract.RecordEntry.COLUMN_TEXT));
holder.title.setText(t);
holder.text.setText(d);
holder.cd.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
Toast.makeText(view.getContext(), ""+position, Toast.LENGTH_SHORT).show();
//holder.ll.setBackgroundColor(Color.parseColor("#000"));
holder.cd.setBackgroundColor(Color.parseColor(view.getResources().getString(R.color.blueGreen)));
return true;
}
});
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_child,parent,false);
return new MyViewHolder(itemView);
}
}

这是我的主要活动

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mdb = new RecordDbHelper(getApplicationContext());
RecyclerView rv = findViewById(R.id.recylerViewId);
rv.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
rv.setItemAnimator(new DefaultItemAnimator());
Cursor c = getCursor();
RecyclerViewAdapter rva = new RecyclerViewAdapter(c);
rv.setAdapter(rva);
}
public Cursor getCursor(){
SQLiteDatabase db = mdb.getReadableDatabase();
String[] projection = {
RecordContract.RecordEntry._ID,  RecordContract.RecordEntry.COLUMN_TEXT,
RecordContract.RecordEntry.COLUMN_TITLE};
String selection = null;
String[] selectionArgs = null;
String tableName = RecordContract.RecordEntry.TABLE_NAME;
Cursor c = db.query(tableName,projection,selection,selectionArgs,null,null,null);
return c;
}

好吧,这显示了回收器视图中的文本 但是当将新数据添加到数据库时,应用程序需要重新启动。它不会自行刷新。

好吧,这显示了回收器视图中的文本

它不会可靠地做到这一点。在onBindViewHolder()中,将moveToNext()替换为moveToPosition(position)。现在,您忽略了position参数,这意味着一旦您开始滚动(尤其是向后滚动(,就会遇到问题。

但是,当新数据添加到数据库时,应用程序需要重新启动。它不会自行刷新。

这与CursorAdapterAdapterView(例如ListView(的工作方式没有什么不同。

当您更新数据库时,您需要获取新的Cursor并将其交给您的RecyclerViewAdapter。然后,您的RecyclerViewAdapter可以调用notifyDataSetChanged()告诉RecyclerView重新绘制自己。

最新更新