2017-09-19 51 views
0

我想使用Android数据绑定库ListView由自定义CursorAdapter填充,但我不知道如何得到它的工作。我看起来很容易实现。Android使用数据绑定库与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); 
     ... 
    } 
} 

当前的行为:
当我运行这段代码,我在列表中向下滚动我上mPlays一个IndexOutOfBoundsException列表。

期望的行为:
我想从ContentProvider使用数据绑定库和CursorAdapter用数据填充ListView。数据绑定库甚至可以使用CursorAdapter?或者您是否建议始终使用RecyclerViewRecyclerView.Adapter

回答

0

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

+0

谢谢,这个解决方案工作。我正在寻找'DataBindingUtil.getBinding(view)'部分。你是否建议使用'RecyvlerView.Adapter'而不是'CursorAdapter'或者它是否适合这种情况?我在Medium上阅读了关于使用'RecyclerView'的文章。 –

+0

RecyclerView是一个较新的小部件,它处理ListView的大部分用例并具有一些附加功能。您还可以在Android版本之间获得稳定性,因为它完全位于支持库内。所以,我认为这是值得研究RecyclerView的未来布局。也就是说,当某件事情对你有用时,真的没有理由改变。 –