RecyclerView使用ItemTouchHelper拖动体验优化

2024/04/19 note 共 1060 字,约 4 分钟

问题

在项目中使用发现,在上下拖动替换时,需要手机拖动条目到目标条目的上方才能完成替换,体验不太好

解决方式

解决方法是重写ItemTouchHelper.CallbackchooseDropTarget方法,自定义拖动识别逻辑

代码如下:

// 优化拖动替换体验,手指在目标控件中心点&&拖动控件覆盖了目标控件中心点,就进行替换  
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  
}  

文档信息

Search

    Table of Contents