我想滑动并拖动&使用ItemTouchHelper类在RecyclerView中删除项目。 RecyclerView放在BottomSheetDialog中。
以下是设置RecyclerView的代码
musicAdapterRecyclerView = new MusicAdapterRecyclerView(this, mainList);
playlistRecyclerView.setLayoutManager(new LinearLayoutManager(this));
playlistRecyclerView.setClickable(true);
playlistRecyclerView.setHasFixedSize(false);
playlistRecyclerView.setAdapter(musicAdapterRecyclerView);
bottomSheetDialog.setContentView(view);
bottomSheetDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
BottomSheetDialog bottomSheetDialog = (BottomSheetDialog) dialogInterface;
FrameLayout bottomSheet = (FrameLayout) bottomSheetDialog
.findViewById(android.support.design.R.id.design_bottom_sheet);
BottomSheetBehavior.from(bottomSheet).setState(BottomSheetBehavior.STATE_COLLAPSED);
}
});
playlistRecyclerView.scrollToPosition(playingIndex);
playlistRecyclerView.setNestedScrollingEnabled(false);
setupItemTouchHelper();
以下是在RecyclerView上设置ItemTouchHelper类的代码
public void setupItemTouchHelper(){
final ItemTouchHelper.Callback callback = new ItemTouchHelper.Callback() {
@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
adapterRecyclerView =(MusicAdapterRecyclerView) recyclerView.getAdapter();
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
return makeMovementFlags(dragFlags, swipeFlags);
}
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
int fromPosition = viewHolder.getAdapterPosition();
int toPosition = target.getAdapterPosition();
if (fromPosition < toPosition) {
for (int i = fromPosition; i < toPosition; i++) {
Collections.swap(mainList, i, i + 1);
}
} else {
for (int i = fromPosition; i > toPosition; i--) {
Collections.swap(mainList, i, i - 1);
}
}
musicAdapterRecyclerView.notifyItemMoved(fromPosition, toPosition);
return true;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
final int pos = viewHolder.getAdapterPosition();
if(pos<0 && pos>=mainList.size()){
return;
}
mainList.remove(pos);
adapterRecyclerView.removeItem(pos);
adapterRecyclerView.notifyItemRemoved(pos);
adapterRecyclerView.notifyItemRangeChanged(pos,mainList.size());
}
@Override
public boolean isLongPressDragEnabled() {
return true;
}
@Override
public boolean isItemViewSwipeEnabled() {
return true;
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
itemTouchHelper.attachToRecyclerView(playlistRecyclerView);
}
问题
当用户在recyclerView上滑动项目时,更新mainList,滑动动画可以正常工作,但除非滚动,否则RecyclerView不会更新。
用于拖放(重新排列项目)的ItemTouchHelper的OnMove()方法未被调用。