Android: animate/translate RecyclerView items using ItemTouchHelper

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

Popular posts from this blog

Working with Android Hierarchy Viewer

Android: Standalone login with SQLiteOpenHelper