ItemTouchHelper:防止越界拖动 [英] ItemTouchHelper: Prevent out of bounds dragging
问题描述
我有一个使用ItemTouchHelper的回收站视图.它允许拖动项目.
I have a recycler view with ItemTouchHelper. It allows dragging the items.
我想将拖动限制在回收站视图的范围内-即,您不能只是将视图拖动到容器外,以使其消失.
I want to limit the dragging to the bounds of recycler view - i.e. you can't just drag the view outside the container, so that it disappears.
我试图像这样检查绝对坐标:
I tried checking the absolute coordinates like this:
@Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
recyclerView.getLocationOnScreen(pos);
int rvY = pos[1];
viewHolder.itemView.getLocationOnScreen(pos);
int vhY = pos[1];
if (rvY > vhY || rvY + recyclerView.getHeight() < vhY + viewHolder.itemView.getHeight()) {
return;
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
...
}
但是后来我遇到了某种程度的渲染一致性-如果我缓慢移动视图,则超出范围时它将停止移动,但是如果我移动得更快,则无论如何它都会离开回收者视图的范围.
but then I run into kinda rendering concurency - if I move the view slowly, it will stop moving when going out of bounds, but if I move faster - then it anyway leaves the recycler view bounds.
有什么想法/方法吗?
推荐答案
dY和dX值必须裁剪为 RecyclerView
的范围:
The dY and dX value must be clipped to the RecyclerView
's bounds:
override fun onChildDraw(c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {
val clippedDx = clip(recyclerView.width, viewHolder.itemView.left, viewHolder.itemView.right, dX)
val clippedDy = clip(recyclerView.height, viewHolder.itemView.top, viewHolder.itemView.bottom, dY)
super.onChildDraw(c, recyclerView, viewHolder, clippedDx, clippedDy, actionState, isCurrentlyActive)
}
private fun clip(size: Int, start: Int, end: Int, delta: Float): Float {
val newStart = start + delta
val newEnd = end + delta
val oobStart = 0 - newStart
val oobEnd = newEnd - size
return when {
oobStart > 0 -> delta + oobStart
oobEnd > 0 -> delta - oobEnd
else -> delta
}
}
这篇关于ItemTouchHelper:防止越界拖动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!