我在我的RecyclerView
中添加了一个自定义的ItemTouchHelper.SimpleCallback
类,以添加“滑动删除”功能,用户可以向左滑动项目,从列表中删除该项。
我将视图可以“滑动”的量限制为视图长度的10%,通过将dX(来自onChildDraw())除以10。但是,用户必须在屏幕上滑动100%的长度才能使项目滑动10%。我想限制滑动(增加项目滑动速度?),以便用户只需滑动屏幕的10%即可使项目滑动10%。请参见下面的照片:
紫色圆圈代表用户触摸。当用户滑过整个屏幕宽度时,该项会滑动10%(红色是在滑动时显示“后面”项目的布局)。如何增加擦拭速度,以便滑动10%的屏幕宽度就足够了,而不是滑动整个屏幕宽度?
这是我的ItemTouchHelper.SimpleCallback类的代码:
public class SwipeDeleteHelper extends ItemTouchHelper.SimpleCallback {
private GameAdapter adapter;
private Drawable icon;
private final ColorDrawable background;
private static final int LIMIT_SWIPE_LENGTH = 10;
public SwipeDeleteHelper(GameAdapter adapter, Context context) {
super(0, ItemTouchHelper.LEFT);
this.adapter = adapter;
icon = ContextCompat.getDrawable(adapter.getContext(),
R.drawable.delete);
background = new ColorDrawable(context.getColor(R.color.colorAccent));
}
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
adapter.deleteItem(position);
}
@Override
public void onChildDraw(@NotNull Canvas c, @NotNull RecyclerView recyclerView, @NotNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
dX = dX/LIMIT_SWIPE_LENGTH;
super.onChildDraw(c, recyclerView, viewHolder, dX,
dY, actionState, isCurrentlyActive);
View itemView = viewHolder.itemView;
int backgroundCornerOffset = 20;
int iconMargin = (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
int iconTop = itemView.getTop() + (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
int iconBottom = iconTop + icon.getIntrinsicHeight();
if(dX < 0) { //left swipe
int iconLeft = itemView.getRight() - iconMargin - icon.getIntrinsicWidth();
int iconRight = itemView.getRight() - iconMargin;
icon.setBounds(iconLeft, iconTop, iconRight, iconBottom);
background.setBounds(itemView.getRight() + ((int) dX) - backgroundCornerOffset,
itemView.getTop(), itemView.getRight(), itemView.getBottom());
} else { //unswiped
background.setBounds(0, 0, 0, 0);
}
background.draw(c);
icon.draw(c);
}
}