2017-09-19 54 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的未來佈局。也就是說,當某件事情對你有用時,真的沒有理由改變。 –