一、ItemTouchHelper是什么
官方解释:This is a utility class to add swipe to dismiss and drag & drop support to RecyclerView.
这是一个支持RecyclerView滑动删除和拖拽的实用工具类
二、如何使用
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(mCallback);
itemTouchHelper.attachToRecyclerView(mRecyclerView);
就这么两行,就可以使用了,不过我们也看见了在创建ItemTouchHelper 对象时,需要传入一个Callback对象,这就是关键之处了.
三、ItemTouchHelper.Callback
ItemTouchHelper.Callback定义在ItemTouchHelper中,是一个抽象类,它还有一个子类SimpleCallback,也是抽象类.
如果只想要一个基本的实现,继承SimpleCallback实现对应的方法即可,这里我们为了了解其工作机制,先来看一看ItemTouchHelper.Callback的常用方法
1)基本的拖动排序与滑动删除需要重写的方法
/**
* 指定可以拖拽(drag)和滑动(swipe)的方向
* ItemTouchHelper.UP、ItemTouchHelper.DOWN
* ItemTouchHelper.LEFT、ItemTouchHelper.RIGHT
* ItemTouchHelper.START、ItemTouchHelper.END
* 若返回0,表示不触发滑动or拖拽
*/
@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
return 0;
}
/**
* 拖拽到新位置时候的回调方法
* @param viewHolder 拖动的ViewHolder
* @param target 目标位置的ViewHolder
*/
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
/**
* 滑动时的回调方法
* @param viewHolder 滑动的ViewHolder
* @param direction 滑动的方向
*/
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
}
2)两个支持方法
/**
* 是否支持长按拖拽,默认为true,表示支持长按拖拽
* 对应长按移动位置功能
* 也可以返回false,手动调用startDrag()方法启动拖拽
*/
@Override
public boolean isLongPressDragEnabled() {
return super.isLongPressDragEnabled();
}
/**
* 是否支持任意位置触摸事件发生时启用滑动操作,默认为true,表示支持滑动
* 对应滑动删除功能
* 也可以返回false,手动调用startSwipe()方法启动滑动
*/
@Override
public boolean isItemViewSwipeEnabled() {
return super.isItemViewSwipeEnabled();
}
四、实现我们自己的回调
ItemTouchHelper.SimpleCallback mCallback =
new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP |
ItemTouchHelper.DOWN | ItemTouchHelper.LEFT |ItemTouchHelper.RIGHT,
ItemTouchHelper.START | ItemTouchHelper.END) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
int fromPosition = viewHolder.getAdapterPosition();//得到拖动ViewHolder的position
int toPosition = target.getAdapterPosition();//得到目标ViewHolder的position
//使用集合工具类Collections,分别把中间所有的item的位置重新交换
if (fromPosition < toPosition) {
for (int i = fromPosition; i < toPosition; i++) {
Collections.swap(mDatas, i, i + 1);
}
} else {
for (int i = fromPosition; i > toPosition; i--) {
Collections.swap(mDatas, i, i - 1);
}
}
//通知Adapter更新状态
mAdapter.notifyItemMoved(fromPosition, toPosition);
return true;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
mDatas.remove(position);//侧滑删除数据
mAdapter.notifyItemRemoved(position); //通知Adapter更新状态
}
@Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
//滑动时改变Item的透明度
final float alpha = 1 - Math.abs(dX) / (float) viewHolder.itemView.getWidth();
viewHolder.itemView.setAlpha(alpha);
viewHolder.itemView.setTranslationX(dX);
}
}
};
继承SimpleCallback ,必须要实现onMove()、onSwiped()方法,同时在构造方法里面需要把拖拽(drag)和滑动(swipe)的方向传递过来(代替了getMovementFlags方法).
五、所有代码
1、布局文件
MainActivity的:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
item的:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ff33b5e5">
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="40dp"
android:gravity="center"
tools:text="别看了,我就是一个TextView" />
</RelativeLayout>
2、MainActivity.java
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private MainAdapter mAdapter;
private List<String> mDatas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
mAdapter = new MainAdapter(this,mDatas);
mRecyclerView.setAdapter(mAdapter);
ItemTouchHelper.SimpleCallback mCallback = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT,
ItemTouchHelper.START | ItemTouchHelper.END) {
@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(mDatas, i, i + 1);
}
} else {
for (int i = fromPosition; i > toPosition; i--) {
Collections.swap(mDatas, i, i - 1);
}
}
mAdapter.notifyItemMoved(fromPosition, toPosition);
return true;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
mDatas.remove(position);
mAdapter.notifyItemRemoved(position);
}
@Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
float dX, float dY, int actionState, boolean isCurrentlyActive) {
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
final float alpha = 1 - Math.abs(dX) / (float) viewHolder.itemView.getWidth();
viewHolder.itemView.setAlpha(alpha);
viewHolder.itemView.setTranslationX(dX);
}
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(mCallback);
itemTouchHelper.attachToRecyclerView(mRecyclerView);
}
private void initData() {
mDatas = new ArrayList<>();
for (int i = 'A'; i < 'Z'; i++) {
mDatas.add("" + (char) i);
}
}
}
3、Adapter中
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MyViewHolder> {
private Context mContext;
private List<String> mDatas;
public MainAdapter(Context context, List<String> mDatas) {
this.mContext = context;
this.mDatas = mDatas;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = View.inflate(mContext, R.layout.item_layout, null);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.tv.setText(mDatas.get(position));
}
@Override
public int getItemCount() {
return mDatas.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv;
public MyViewHolder(View view) {
super(view);
tv = (TextView)itemView.findViewById(R.id.tv);
}
}
}
六、效果图及总结
ItemTouchHelper不仅仅支持LinearLayoutManager,对于GridLayoutManager和StaggeredGridLayoutManager也都是支持的,像新闻app中常见的拖动标签效果,利用ItemTouchHelper可以很轻松的实现.