没有人在乎你在深夜痛哭,也没有人在乎你辗转反侧要熬几个秋。外人只看结果,自己独撑整个过程。等我们明白了这个道理,便不会再别人面前矫情,四处诉说以求宽慰
这篇文章主要来讲讲recyclerVeiw的item的滑动跟拖拽
先上图
策划与拖拽.gif主要是重写ItemTouchHelper这个类,具体的实现的方法我在这里也注视了,最后将ItemTouchHelper跟recyclerView关联。
itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
//用于设置拖拽和滑动的方向
@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags = 0, swipeFlags = 0;
if (recyclerView.getLayoutManager() instanceof StaggeredGridLayoutManager || recyclerView.getLayoutManager() instanceof GridLayoutManager) {
dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
} else if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
//设置侧滑方向为从左到右和从右到左都可以
swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
}
return makeMovementFlags(dragFlags, swipeFlags);
}
//长摁item拖拽时会回调这个方法
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
int from = viewHolder.getAdapterPosition();
int to = target.getAdapterPosition();
Collections.swap(meiziList, from, to);
mAdapter.notifyItemMoved(from, to);
return true;
}
//这里处理滑动删除
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
mAdapter.removeItem(viewHolder.getAdapterPosition());
}
//当item拖拽开始时调用
@Override
public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
super.onSelectedChanged(viewHolder, actionState);
if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
viewHolder.itemView.setBackgroundColor(Color.LTGRAY);
}
}
//当item拖拽完成时调用
@Override
public boolean isLongPressDragEnabled() {
//不需要长按拖动,
return true;
}
@Override
public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
super.clearView(recyclerView, viewHolder);
viewHolder.itemView.setBackgroundColor(Color.WHITE);
}
//当item视图变化时调用
@Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
viewHolder.itemView.setAlpha(1 - Math.abs(dX) / screenwidth);
//根据item滑动偏移的值修改item透明度。screenwidth是我提前获得的屏幕宽度
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
});
itemTouchHelper.attachToRecyclerView(recycler);
当然平常开发中这些功能不是很常见
https://github.com/yanzhenjie/SwipeRecyclerView 这个是开发中很常见的策划实例
网友评论