我想使用自定义ListView
填充CursorAdapter
的Android数据绑定库,但我无法弄清楚如何让它工作。我似乎很容易实现。
这就是我现在所拥有的:
public class PlayCursorAdapter extends CursorAdapter {
private List<Play> mPlays;
PlayCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
mPlays = new ArrayList<>();
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
ListItemPlayBinding binding = ListItemPlayBinding.inflate(LayoutInflater.from(context), parent, false);
Play play = new Play();
binding.setPlay(play);
mPlays.add(play);
return binding.getRoot();
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
int timeIndex = cursor.getColumnIndexOrThrow(PlayEntry.COLUMN_TIME);
...
long time = cursor.getLong(timeIndex);
...
Play play = mPlays.get(cursor.getPosition());
play.setTime(time);
...
}
}
当前行为:
当我运行此代码并向下滚动列表时,我会在 mPlays 列表中获得IndexOutOfBoundsException
。
所需行为
我想使用数据绑定库和ListView
使用来自ContentProvider
的数据填充CursorAdapter
。是否可以将数据绑定库与CursorAdapter
一起使用?或者,您是否建议始终使用RecyclerView
和RecyclerView.Adapter
?
答案 0 :(得分:1)
您应该可以通过删除mPlays列表来避免此问题:
public class PlayCursorAdapter extends CursorAdapter {
PlayCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
ListItemPlayBinding binding = ListItemPlayBinding.inflate(LayoutInflater.from(context), parent, false);
Play play = new Play();
binding.setPlay(play);
return binding.getRoot();
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
int timeIndex = cursor.getColumnIndexOrThrow(PlayEntry.COLUMN_TIME);
...
long time = cursor.getLong(timeIndex);
...
ListItemPlayBinding binding = DataBindingUtil.getBinding(view);
Play play = binding.getPlay();
play.setTime(time);
...
}
}
这假设您不仅希望每次bindView()时都实例化一个新的Play。