BottomSheetDialogFragment嵌套Recyclerview滑动冲突的问题

1,666 阅读1分钟

BottomSheetDialogFragment嵌套Recyclerview会导致Recyclerview无法下拉,解决方案如下 在fragment的

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

//滑动到顶部则 isNestedScrollingEnabled设置成true
//否则设置成false
    binding?.xrvContent?.addOnScrollListener(object : OnScrollListener() {  
  
        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {  
            totalScrollY += dy  
            binding?.root?.isNestedScrollingEnabled = (totalScrollY != 0)  
            if (binding?.root?.isNestedScrollingEnabled == false) {  
                canDrag()  
            }  
        }  
})

    //如果点击的不是recyclerview里 则把根布局isNestedScrollingEnabled设置成false 
    //如果点击在recyclerview则 isNestedScrollingEnabled设置成true
    //同时设置成false的时候要刷新 BottomSheetBehavior 否则不生效
    binding?.root?.setOnTouchListener { _, motionEvent ->  
        if (motionEvent.action == MotionEvent.ACTION_DOWN) {  
            // 获取点击坐标  
            val x = motionEvent.rawX.toInt()  
            val y = motionEvent.rawY.toInt()  
            binding?.root?.isNestedScrollingEnabled = isTouchPointInView(binding?.xrvContent, x, y)  
            if (binding?.root?.isNestedScrollingEnabled == false) {  
                canDrag()  
            }  
        }  
        false  
    }

}

//刷新 可拖拽了  
fun canDrag() {  
(dialog as? BottomSheetDialog)?.apply {  
val coordinator: CoordinatorLayout? = findViewById(R.id.coordinator)  
val bottomSheet: FrameLayout? = findViewById(R.id.design_bottom_sheet)  
if (coordinator != null && bottomSheet != null) behavior.onLayoutChild(coordinator, bottomSheet, ViewCompat.LAYOUT_DIRECTION_RTL)  
}  
}

fun isTouchPointInView(view: View?, x: Int, y: Int): Boolean {  
if (view == null) return false  
val location = IntArray(2)  
view.getLocationOnScreen(location)  
val left = location[0]  
val top = location[1]  
val right = left + view.measuredWidth  
val bottom = top + view.measuredHeight  
  
return y in top..bottom && x >= left && x <= right  
}