ItemTouchHelper.Callback callback = new ItemMoveHelper(ItemTouchHelper.UP |
ItemTouchHelper.DOWN, ItemTouchHelper.START | ItemTouchHelper.END);
ItemTouchHelper helper = new ItemTouchHelper(callback);
helper.attachToRecyclerView(mRecyclerView);
ItemTouchHelper moves the items' of a recyclerView to translateX/Y properties to
reposition them
class ItemMoveHelper extends ItemTouchHelper.SimpleCallback {
public ItemMoveHelper(int dragDirs, int swipeDirs) {
super(dragDirs, swipeDirs);
}
@Override public boolean onMove(RecyclerView recyclerView,
RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
Collections.swap(mBagList, viewHolder.getAdapterPosition(), target.getAdapterPosition());
mAdapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
return false;
}
@Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
Log.i(getClass().getSimpleName(), " direction = "+ direction);
mBagList.remove(viewHolder.getAdapterPosition());
totalItems.setText(getString(R.string.bag_title_for_total_items) + mBagList.size());
mAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
}
@Override public void onChildDraw(Canvas c, RecyclerView recyclerView,
RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState,
boolean isCurrentlyActive) {
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
float width = (float) viewHolder.itemView.getWidth();
float alpha = 1.0f - Math.abs(dX) / width;
viewHolder.itemView.setAlpha(alpha);
viewHolder.itemView.setTranslationX(dX);
} else {
super.onChildDraw(c, recyclerView, viewHolder, dX, dY,
actionState, isCurrentlyActive);
}
}
}
Comments
Post a Comment