问题
在项目中使用发现,在上下拖动替换时,需要手机拖动条目到目标条目的上方才能完成替换,体验不太好
解决方式
解决方法是重写ItemTouchHelper.Callback
的chooseDropTarget
方法,自定义拖动识别逻辑
代码如下:
// 优化拖动替换体验,手指在目标控件中心点&&拖动控件覆盖了目标控件中心点,就进行替换
override fun chooseDropTarget(
selected: RecyclerView.ViewHolder,
dropTargets: MutableList<RecyclerView.ViewHolder>,
curX: Int,
curY: Int
): RecyclerView.ViewHolder? {
var winner: RecyclerView.ViewHolder? = null
val currCenterX = curX + selected.itemView.width / 2
val currCenterY = curY + selected.itemView.height / 2
val targetsSize = dropTargets.size
for (i in 0 until targetsSize) {
val target = dropTargets[i]
val targetCenterX = target.itemView.right - target.itemView.width / 2
val targetCenterY = target.itemView.bottom - target.itemView.height / 2
if (currCenterX > target.itemView.left && currCenterX < target.itemView.right &&
currCenterY > target.itemView.top && currCenterY < target.itemView.bottom &&
targetCenterX > target.itemView.left && targetCenterX < target.itemView.right &&
targetCenterY > target.itemView.top && targetCenterY < target.itemView.bottom
) {
winner = target
}
}
return winner
}
文档信息
- 本文作者:itlgl
- 本文链接:https://itlgl.com/note/2024/04/19/issues-57/
- 版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)