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
相关推荐
极客小云5 小时前
【深入理解 Android 中的 build.gradle 文件】Juskey iii5 小时前
Android Studio Electric Eel | 2022.1.1 Patch 2 版本下载Android技术之家5 小时前
2025年度Android行业总结:AI驱动生态重构,跨端融合开启新篇洞见前行5 小时前
Android第二代加固技术原理详解(附源码)风清云淡_A5 小时前
【JetCompose】入门教程实战基础案例01之显隐动画2501_916007475 小时前
iPhone APP 性能测试怎么做,除了Instruments还有什么工具?2501_915106325 小时前
Windows 环境下有哪些可用的 iOS 上架工具, iOS 上架工具的使用方式冬奇Lab6 小时前
稳定性性能系列之六——Java异常与JE分析实战爱装代码的小瓶子7 小时前
【c++进阶】c++11的魔法:从模板到可变模板.lxysbly8 小时前
安卓MD模拟器下载指南2026