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
相关推荐
sang_xb6 小时前
Android 系统的权限管理最佳实践用户41659673693556 小时前
Jetpack Compose 中 AndroidView 的生命周期管理与 WebView 实践用户83352502537856 小时前
android 后台应用申请音频焦点失败zhuhai06137 小时前
Android Socket 深度剖析:从原理到实战毕设源码-朱学姐7 小时前
【开题答辩全过程】以 基于Android的留守儿童贫困资助管理系统的设计与实现为例,包含答辩的问题和答案愤怒的代码7 小时前
深入理解 IdleHandler:从启动优化到内存管理恋猫de小郭7 小时前
OpenAI :你不需要跨平台框架,只需要在 Android 和 iOS 上使用 Codex路在脚下,梦在心里7 小时前
net学习总结走在路上的菜鸟7 小时前
Android学Dart学习笔记第二十节 类-枚举星光一影7 小时前
合成植物大战僵尸 安卓原生APP Cocos游戏 支持Sigmob