Android 是否可以像ListView一样在recycleview中设置CursorAdapter?
到目前为止,我还没有谷歌出一个解决方案来替换我项目中的listview,因为我需要使用与sqlite链接的游标 老办法如下:Android 是否可以像ListView一样在recycleview中设置CursorAdapter?,android,android-recyclerview,android-support-library,Android,Android Recyclerview,Android Support Library,到目前为止,我还没有谷歌出一个解决方案来替换我项目中的listview,因为我需要使用与sqlite链接的游标 老办法如下: listview.setAdapter(cursorAdapter)通过这种方式,我可以让光标处理数据库中的数据 但是现在,recycleview.setAdapter(recycleview.adapter)它无法识别扩展BaseAdapter的适配器 任何人都可以帮我一把吗?新的RecyclerView与新的RecyclerView.Adapter基类一起工作。 因此
listview.setAdapter(cursorAdapter)
通过这种方式,我可以让光标处理数据库中的数据
但是现在,recycleview.setAdapter(recycleview.adapter)
它无法识别扩展BaseAdapter的适配器
任何人都可以帮我一把吗?新的
RecyclerView
与新的RecyclerView.Adapter
基类一起工作。
因此它不适用于光标或适配器
目前,没有可用的RecyclerView.Adapter的默认实现
谷歌可能会在正式发布后添加它。自己实现其实很简单:
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...
}
}
公共类游标适配器扩展了RecyclerView.Adapter{
游标数据游标;
@凌驾
public int getItemCount(){
返回(dataCursor==null)?0:dataCursor.getCount();
}
公共void changeCursor(游标){
游标old=swapCursor(游标);
如果(旧!=null){
old.close();
}
}
公共游标交换游标(游标游标){
if(dataCursor==游标){
返回null;
}
游标oldCursor=dataCursor;
this.dataCursor=游标;
如果(光标!=null){
this.notifyDataSetChanged();
}
返回光标;
}
私有对象getItem(int位置){
数据光标。移动位置(位置);
//从dataCursor加载数据并返回它。。。
}
}
是的,我在github中找到了一个解决方案,但是官方版本在各个方面都会更好,我最好等一等。@machinezhou你能分享github项目吗?@josedlujan这是github项目的链接,呃,这不是我的意思,伙计,后来我确实在github上发现了一个项目,其中cursorAdapter是由开发人员自己实现的。但这并不是那么容易,我不确定它是否会出现错误或意外。因此,出于我自身的能力和稳定性考虑,我宁愿等待正式发布。@machinezhou我不认为他们会为它添加正式发布,到目前为止,这对我来说一直是完美的。我感到,由于“UI线程上没有DB工作”,因此不会有正式的实现自从《漫步者》以来,他们一直在推动的氛围。无论如何,对于这里的解决方案,在我看到的其他实现中,您可能希望检查移动光标或光标状态所导致的潜在错误。到目前为止,我看到的实现只是在这种情况下抛出异常,这对我来说似乎不太合适。我很惊讶,但这个简单的解决方案对我来说完美无瑕。当我得到日志时,会调用Tryed和onBindViewHolder,但什么都没有显示。请看我的答案:很好的技巧:)可能重复