class DraggableBottomView(
context: Context,
attrs: AttributeSet? = null,
) :LinearLayout(context, attrs, 0) {
private var gestureDetector: GestureDetectorCompat
private var initialY = 0f
private var initialX = 0f
private var initialHeight = 0
private val minHeight: Int
private val maxHeight: Int
private val touchSlop: Int //触摸滑动距离
private var isDragging = false // 是否正在拖动
private var isUpOrDown = "up" // up向上 down 向下
init {
minHeight = CommonUtil.dpToPx(context,200)
maxHeight = CommonUtil.dpToPx(context,500)
touchSlop = ViewConfiguration.get(context).scaledTouchSlop
gestureDetector = GestureDetectorCompat(context, object : GestureDetector.SimpleOnGestureListener() {
override fun onDown(e: MotionEvent): Boolean {
initialY = e.rawY
initialX = e.rawX
initialHeight = height
return true
}
})
}
override fun onTouchEvent(event: MotionEvent): Boolean {
gestureDetector.onTouchEvent(event)
when (event.action) {
MotionEvent.ACTION_MOVE -> {
val dy = event.rawY - initialY
val dx = event.rawX - initialX
if (Math.abs(dy) > touchSlop && Math.abs(dy)>Math.abs(dx)){
isUpOrDown = if (dy < 0f) "up" else "down"
isDragging = true
}else{
isDragging = false
}
// 设置跟随手指滑动
val newHeight = (initialHeight - dy).toInt()
val clampedHeight = newHeight.coerceIn(minHeight, maxHeight)
val params = layoutParams as ViewGroup.LayoutParams
params.height = clampedHeight
layoutParams = params
requestLayout()
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
if (isDragging) {
// 滑动松手后的逻辑
if (isUpOrDown == "up") {
animateHeightChange(maxHeight)
} else {
// 固定到初始位置位置
animateHeightChange(minHeight)
}
isDragging = false
} else {
}
}
}
return true
}
private fun animateHeightChange(targetHeight: Int) {
val valueAnimator = ValueAnimator.ofInt(height, targetHeight)
valueAnimator.duration = 200 // 动画持续时间,可根据需要调整
valueAnimator.addUpdateListener { animator ->
val animatedValue = animator.animatedValue as Int
val params = layoutParams as ViewGroup.LayoutParams
params.height = animatedValue
layoutParams = params
requestLayout()
}
valueAnimator.start()
}
}
Android 拖转改变视图高度
FlyingWDX2025-01-22 14:13
相关推荐
tangweiguo030519871 分钟前
Kotlin 实现 Android 网络状态检测工具类nvvas1 小时前
Android Studio JAVA开发按钮跳转功能怪兽20141 小时前
Android多进程通信机制叶羽西2 小时前
Android CarService调试操作千里马-horse2 小时前
在android中 spdlog库的log如何在控制台上输出Zender Han2 小时前
《从零搭建现代 Android 模块化架构项目(2025 最新实践)》Digitally2 小时前
如何从电脑上卸载安卓应用程序Mr YiRan3 小时前
多线程性能优化基础liyi_hz20083 小时前
O2OA (翱途)开发平台新版本发布预告:架构升级、性能跃迁、功能全面进化Huangyi3 小时前
第一节:Flow的基础知识