I want to implement dragging the cards in such a way that the rearrangement of the cards starts when the card that I am dragging does not completely overlap the element, but only 50%.
Check out an example:
Now, for the right card to move to the left, I need to completely overlap it with the one I am dragging.
I tried overriding this method from ItemTouchHelper.Callback:
public float getMoveThreshold(@NonNull ViewHolder viewHolder) {
return .5f;
}
But it didn't help.
So how can I make the swap happen at 50% and not at 100% overlap?
After many attempts, I found the solution myself:
You need to override the chooseDropTarget method from ItemTouchHelper.Callback.
This is how I did it:
// 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
}
How it works:
I am calculating the offset of the selected view using the factor and width/height. After that I create new borders (left, right, top, bottom), add an offset to the borders of the selected view and then use them instead of the original in the method
Important: