Recyclerview拖拽和侧滑删除

build.gradle导包:

compile 'com.android.support:recyclerview-v7:+'

基本使用:

RecyclerView recyclerView = (RecyclerView) findView(R.id.id_recyclerview);;
RecyclerListAdapter adapter = new RecyclerListAdapter(getActivity(),this);
//如果可以确定每个item的高度是固定的,设置这个选项可以提高性能
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

//以下为拖拽和侧滑删除功能代码(接上):
/*
    拖拽和侧滑删除的功能我们要借助ItemTouchHelper这个类,我们只需要创建出一个ItemTouchHelper对象,
    然后调用mItemTouchHelper.attachToRecyclerView(recyclerView);就可以了。
    我们看一下ItemTouchHelper的构造方法,他需要一个Callback
        public ItemTouchHelper(Callback callback) {
            mCallback = callback;
        }
    这个Callback是ItemTouchHelper的内部类,所以我们需要写一个类继承自ItemTouchHelper.Callback ,然后重写里面的方法
    所以这个Callback就是SimpleItemTouchHelperCallback
    */
    ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(adapter);
    mItemTouchHelper = new ItemTouchHelper(callback);
    mItemTouchHelper.attachToRecyclerView(recyclerView);


/**
 我们看一下ItemTouchHelper的构造方法,他需要一个Callback
 public ItemTouchHelper(Callback callback) {
 mCallback = callback;
 }
 这个Callback是ItemTouchHelper的内部类,所以我们需要写一个类继承自ItemTouchHelper.Callback ,然后重写里面的方法
 */
public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {

public static final float ALPHA_FULL = 1.0f;

private final ItemTouchHelperAdapter mAdapter;

public SimpleItemTouchHelperCallback(ItemTouchHelperAdapter adapter) {
    mAdapter = adapter;
}
/*
为了支持长按 RecyclerView item 对其进行拖动, isLongPressDragEnabled() 应该返回true.
此外在开始拖拽时 ItemTouchHelper.startDrag(RecyclerView.ViewHolder) 将会被调用。
 */
@Override
public boolean isLongPressDragEnabled() {
    return true;
}
/*
如果在viwe中可以随意滑动,isItemViewSwipeEnabled() 函数返回true.
此外手动拖动时 ItemTouchHelper.startSwipe(RecyclerView.ViewHolder) 会被调用。
 */
@Override
public boolean isItemViewSwipeEnabled() {
    return true;
}

/**这个方法是用来设置我们拖动的方向以及侧滑的方向的*/
@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
    // //如果是GridView样式的RecyclerView
    if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
        //设置拖拽方向为上下左右
        final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
        //不支持侧滑
        final int swipeFlags = 0;
        return makeMovementFlags(dragFlags, swipeFlags);
    } else {      //如果是ListView样式的RecyclerView
        //设置拖拽方向为上下
        final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
        //设置侧滑方向为从左到右和从右到左都可以
        final int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
        //将方向参数设置进去
        return makeMovementFlags(dragFlags, swipeFlags);
    }
}
/**当我们拖动item时会回调此方法*/
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder source, RecyclerView.ViewHolder target) {
    if (source.getItemViewType() != target.getItemViewType()) {
        return false;
    }

    mAdapter.onItemMove(source.getAdapterPosition(), target.getAdapterPosition());
    return true;
}
/**当我们侧滑item时会回调此方法*/
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int i) {
    mAdapter.onItemDismiss(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) {
        //根据侧滑的位移来修改item的透明度
        final float alpha = ALPHA_FULL - Math.abs(dX) / (float) viewHolder.itemView.getWidth();
        viewHolder.itemView.setAlpha(alpha);
        viewHolder.itemView.setTranslationX(dX);
    } else {
        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
    }
}
/**当状态改变时回调此方法*/
@Override
public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
    //当前状态不是idel(空闲)状态时,说明当前正在拖拽或者侧滑
    if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
        //看看这个viewHolder是否实现了onStateChangedListener接口
        if (viewHolder instanceof ItemTouchHelperCallbackOnStateChange) {
            ItemTouchHelperCallbackOnStateChange itemViewHolder = (ItemTouchHelperCallbackOnStateChange) viewHolder;
            //当发生移动或者拖拽时,我们应该回调ItemViewHolder中onItemSelected方法让item做进一步操作
            itemViewHolder.onItemSelected();
        }
    }

    super.onSelectedChanged(viewHolder, actionState);
}
/**当用户拖拽完或者侧滑完一个item时回调此方法,用来清除施加在item上的一些状态*/
@Override
public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
    super.clearView(recyclerView, viewHolder);

    viewHolder.itemView.setAlpha(ALPHA_FULL);

    if (viewHolder instanceof ItemTouchHelperCallbackOnStateChange) {
        // Tell the view holder it's time to restore the idle state
        ItemTouchHelperCallbackOnStateChange itemViewHolder = (ItemTouchHelperCallbackOnStateChange) viewHolder;
        itemViewHolder.onItemClear();
    }
}
}

public class RecyclerListAdapter extends RecyclerView.Adapter<RecyclerListAdapter.ItemViewHolder>
    implements ItemTouchHelperAdapter {
/*
当item被拖拽或者侧滑的时候会回调onMove和onSwiped方法,所以我们需要同时Adapter 实现 ItemTouchHelperAdapter接口,
对mItems数据做出交换onItemMove()或者删除onItemDismiss()的操作
 */

private final List<String> mItems = new ArrayList<>();

private final OnStartDragListener mDragStartListener;

    public RecyclerListAdapter(Context context, OnStartDragListener dragStartListener) {
    mDragStartListener = dragStartListener;
    mItems.addAll(Arrays.asList(context.getResources().getStringArray(R.array.dummy_items)));
}

@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_main, parent, false);
    ItemViewHolder itemViewHolder = new ItemViewHolder(view);
    return itemViewHolder;
}

@Override
public void onBindViewHolder(final ItemViewHolder holder, int position) {
    holder.textView.setText(mItems.get(position));

    // 拖动图标即可拖拽整个item
    holder.handleView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
                mDragStartListener.onStartDrag(holder);
            }
            return false;
        }
    });
}

@Override
public void onItemDismiss(int position) {
    //删除mItems数据
    mItems.remove(position);
    //删除RecyclerView列表对应item
    notifyItemRemoved(position);
}

@Override
public boolean onItemMove(int fromPosition, int toPosition) {
    //交换mItems数据的位置
    Collections.swap(mItems, fromPosition, toPosition);
    //交换RecyclerView列表中item的位置
    notifyItemMoved(fromPosition, toPosition);
    return true;
}

@Override
public int getItemCount() {
    return mItems.size();
}

/**
 * Simple example of a view holder that implements {@link ItemTouchHelperCallbackOnStateChange} and has a
 * "handle" view that initiates a drag event when touched.
 */

public static class ItemViewHolder extends RecyclerView.ViewHolder implements
        ItemTouchHelperCallbackOnStateChange {
    //根据上面的SimpleItemTouchHelperCallback中的onSelectedChanged()和clearView()参数中的viewHolder,所以需要在这里实现ItemTouchHelperCallbackOnStateChange接口,实现这两个方法的回调
    public final TextView textView;
    public final ImageView handleView;

    public ItemViewHolder(View itemView) {
        super(itemView);
        textView = (TextView) itemView.findViewById(R.id.text);
        handleView = (ImageView) itemView.findViewById(R.id.handle);
    }

    @Override
    public void onItemSelected() {
        itemView.setBackgroundColor(Color.LTGRAY);
    }

    @Override
    public void onItemClear() {
        itemView.setBackgroundColor(0);
    }
}
}

public interface ItemTouchHelperCallbackOnStateChange {


    void onItemSelected();



    void onItemClear();
}

/**
 * 当item被拖拽或者侧滑的时候会回调onMove和onSwiped方法,所以我们需要同时Adapter做出相应的改变,对mItems数据做出交换或者删除的操作,因此我们需要一个回调接口来继续回调Adapter中的方法
 *
 * @author Paul Burke (ipaulpro)
 */

public interface ItemTouchHelperAdapter {


    boolean onItemMove(int fromPosition, int toPosition);

    void onItemDismiss(int position);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值