代码之家  ›  专栏  ›  技术社区  ›  Jelmer Brands

Android使用带有CursorAdapter的数据绑定库

  •  1
  • Jelmer Brands  · 技术社区  · 9 年前

    我想使用Android数据绑定库和 ListView CursorAdapter ,但我不知道如何让它工作。我似乎要完成这么简单的事情。

    这就是我现在拥有的:

    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);
            ...
        }
    }
    


    当我运行此代码并在列表中向下滚动时,我得到一个 IndexOutOfBoundsException 上 mPlays 列表


    我想填充一个 列表视图 ContentProvider 使用数据绑定库和 游标适配器 . 甚至可以将数据绑定库与 RecyclerView 和a RecyclerView.Adapter ?

    1 回复  |  直到 9 年前
        1
  •  1
  •   George Mount    9 年前

    您应该能够通过消除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()时实例化一个新剧。