2017-09-19 12 views
0

CursorAdapterが入力されているListViewのAndroidデータバインディングライブラリを使用したいが、それを動作させる方法がわからない。私は達成するのはとても簡単なことです。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を取得します。

望ましい行動:
私はデータバインディングライブラリを使用してContentProviderCursorAdapterからデータを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)'の部分を探していました。あなたは 'CursorAdapter'の代わりに' RecyvlerView.Adapter'を使うことをお勧めしますか?それともこの状況のた​​めに過剰ですか?私は 'RecyclerView'を使ってあなたの投稿をMediumで読むことができます。 –

+0

RecyclerViewは、ListViewのほとんどの使用例を処理する新しいウィジェットであり、いくつかの追加機能があります。また、サポートライブラリ内に完全に含まれているため、Androidのバージョン間でも安定性が得られます。だから、将来のレイアウトのためにRecyclerViewを検討する価値があると思います。つまり、何かがうまくいくと変わる理由はありません。 –

関連する問題