我在ItemTouchHelper.SimpleCallback
上添加了一个自定义RecyclerView
类,以添加“轻扫时关闭”功能,用户可以在其中向左滑动项目,然后从列表中删除该项目。
通过将dX(来自onChildDraw())除以10,我将视图可以“滑动”到左的长度限制为视图长度的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);
}
}
答案 0 :(得分:1)
覆盖getSwipeThreshold以返回0.1f:
@Override
public float getSwipeThreshold(@NonNull RecyclerView.ViewHolder viewHolder) {
return 0.1f;
}
答案 1 :(得分:0)
我发现将getSwipeThreshold()
调整为0.1f
是不够的。我也推翻了public float getSwipeVelocityThreshold(float defaultValue)
返回1f.
根据文档(https://developer.android.com/reference/kotlin/androidx/recyclerview/widget/ItemTouchHelper.Callback#getswipevelocitythreshold),值越低,滑动和移除的难度就越大,因为您必须拖动更多的对角线,而更多的是直线。我将1f
的值0.5f
与getSwipeThreshold()
方法一起使用,为自己实现了“清除滑动”的理想阈值。 >