RecyclerView ItemTouchHelper.Callback:拖动交换条件
Posted
技术标签:
【中文标题】RecyclerView ItemTouchHelper.Callback:拖动交换条件【英文标题】:RecyclerView ItemTouchHelper.Callback: Dragging swap condition 【发布时间】:2021-05-01 04:18:09 【问题描述】:我想以这样一种方式实现卡片的拖动,当我拖动的卡片没有完全重叠元素,但只有 50% 时,卡片的重新排列开始。
查看示例:
现在,要让右侧卡片向左移动,我需要将它与我拖动的卡片完全重叠。
我尝试从 ItemTouchHelper.Callback 覆盖此方法:
public float getMoveThreshold(@NonNull ViewHolder viewHolder)
return .5f;
但这并没有帮助。
那么我怎样才能使交换发生在 50% 而不是 100% 重叠?
【问题讨论】:
【参考方案1】:经过多次尝试,我自己找到了解决办法:
您需要覆盖 ItemTouchHelper.Callback 中的 chooseDropTarget 方法。
我就是这样做的:
// x ≥ 0.5 (if less than 0.5, it will shake due to constant overlap)
val DRAG_THRESHOLD_PERSENT = 0.5
override fun chooseDropTarget(
selected: ViewHolder,
targets: MutableList<ViewHolder>,
curX: Int, curY: Int
): ViewHolder?
val verticalOffset = (selected.itemView.height * DRAG_THRESHOLD_PERSENT).toInt()
val horizontalOffset = (selected.itemView.width * DRAG_THRESHOLD_PERSENT).toInt()
val left = curX - horizontalOffset
val right = curX + selected.itemView.width + horizontalOffset
val top = curY - verticalOffset
val bottom = curY + selected.itemView.height + verticalOffset
var winner: ViewHolder? = null
var winnerScore = -1
val dx = curX - selected.itemView.left
val dy = curY - selected.itemView.top
val targetsSize = targets.size
for (i in 0 until targetsSize)
val target = targets[i]
if (dx > 0)
val diff = target.itemView.right - right
if (diff < 0 && target.itemView.right > selected.itemView.right)
val score = abs(diff)
if (score > winnerScore)
winnerScore = score
winner = target
if (dx < 0)
val diff = target.itemView.left - left
if (diff > 0 && target.itemView.left < selected.itemView.left)
val score = abs(diff)
if (score > winnerScore)
winnerScore = score
winner = target
if (dy < 0)
val diff = target.itemView.top - top
if (diff > 0 && target.itemView.top < selected.itemView.top)
val score = abs(diff)
if (score > winnerScore)
winnerScore = score
winner = target
if (dy > 0)
val diff = target.itemView.bottom - bottom
if (diff < 0 && target.itemView.bottom > selected.itemView.bottom)
val score = abs(diff)
if (score > winnerScore)
winnerScore = score
winner = target
return winner
工作原理: 我正在使用因子和宽度/高度计算所选视图的偏移量。之后,我创建新边框(左、右、上、下),为所选视图的边框添加偏移量,然后在方法中使用它们代替原来的
重要:
你不应该调用 super 系数必须大于0.5【讨论】:
【参考方案2】:我没有解决方案,但我仍然想分享我的观察。 看起来您从 getMoveThreshold() 方法返回的任何低于 1 的值都不会改变默认行为,但实际上高于 1 的值会改变。
【讨论】:
以上是关于RecyclerView ItemTouchHelper.Callback:拖动交换条件的主要内容,如果未能解决你的问题,请参考以下文章
RecyclerView系列:RecyclerView嵌套RecyclerView(BaseRecyclerViewAdapterHelper实现)