场景:
近期做的TODO APP需要在主页添加一个功能,就是可以左滑删除,右滑完成。看了一下当前其他人做的例如仿探探式的效果,核心功能基本一样,但是和我预想的还是有少量区别,于是干脆自己重头学一遍如何自定义layout并且实现我所期望的功能。顺便写个傻瓜式教程,总结一下前人的经验。
需要:
Android Studio, RecyclerView
方法:
1. ItemTouchHelper
首先来看一下这个类的官方定义:
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 interactions are enabled and also receives events when user performs these actions.
Depending on which functionality you support, you should override onMove(RecyclerView, ViewHolder, ViewHolder)
and / or onSwiped(ViewHolder, int)
.
This class is designed to work with any LayoutManager but for certain situations, it can be optimized for your custom LayoutManager by extending methods in the ItemTouchHelper.Callback
class or implementing ItemTouchHelper.ViewDropHandler
interface in your LayoutManager.
By default, ItemTouchHelper moves the items' translateX/Y properties to reposition them. You can customize these behaviors by overriding onChildDraw(Canvas, RecyclerView, ViewHolder, float, float, int, boolean)
or onChildDrawOver(Canvas, RecyclerView, ViewHolder, float, float, int, boolean)
.
Most of the time you only need to override onChildDraw
.
可以看出,这是一个可以支持RecyclerView实现用于滑动删除,拖拽效果的类。
他和recyclerview配合工作以确定什么样的交互方式可以使用,并且创建回调来对这些事件来进行接收
我们可以复写onMove和onSwiped来定义它的功能
这个类通常需要配合LayoutManager来使用
ItemHelper会将item重新移动,可以通过复写onChildDraw和onChildDrawOver来重新定义其行为
ok,我们直接用一下试试看
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview); recyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false)); MyAdapter adapter = new MyAdapter(list); recyclerView.setAdapter(adapter); ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() { @Override public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) { return 0; } @Override public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { return false; } @Override