--- by Anwei.shi
背景介绍:
Android 应用开发中避免不了对容器中的各个Item的进行拖拽排序等操作,比如锤子手机中著名的OneStep功能(拖拽),以及Android 系统中语言设置菜单的快速排序功能。前段时间由于项目需求,需要对悬浮球中的菜单项实现如上的快速拖动排序删除等功能。具体实现:
1.拖拽排序
参看AndroidSetting语言设置项源码,主要为LocaleDragAndDropAdapter.java和LocaleRecyclerView.java。在这两个类中主要是利用了RecycleView的辅助类ItemTouchHelper.class进行相关的拖拽排序等功能。该类的Google官方描述:
This is a utility class to add swipe to dismiss and drag & drop support to RecyclerView. It works with a RecyclerView and a Callback class, which configures what type of interaction are enabledand also receives events when user performs these actions. Depending on which functionality you support, you should override { @link Callback#onMove(RecyclerView, ViewHolder, ViewHolder)} and / or{ @linkCallback#onSwiped(ViewHolder, int)}.
从以上可以看出实现拖拽必须重写onMove()和onSwiped()这两个方法。Android的布局方式为上下左右,该如何控制拖拽的方向呢?继续阅读Android源码,有getMovementFlags(RecyclerViewrecyclerView, RecyclerView.ViewHolder viewHolder)的抽象方法,其描述为
Should return a composite flag which defines the enabledmove directions in each state (idle, swiping, dragging).
大意是返回的是一个具有移动方向的值flag。根据以上内容,实现如下代码:
private ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
@Override
public int getMovementFlags(RecyclerViewrecyclerView, RecyclerView.ViewHolder viewHolder) {
//首先回调的方法返回int表示是否监听该方向
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;//拖拽
int swipeFlags = ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT;//侧滑删除
return makeMovementFlags(dragFlags, swipeFlags);
}
@Override
public boolean onMove(RecyclerView recyclerView