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
相关推荐
程序员陆业聪36 分钟前
别再说 Flutter 是唯一选择了——KMP 正在悄悄抢走它的地盘三少爷的鞋1 小时前
2026 已过 1/3:事豫则立,不预则废——关于架构、协程与边界的思考冬奇Lab1 小时前
Android 15 音频子系统(八):Audio HAL 与硬件接口——音频数据的最后一公里黄林晴4 小时前
Compose Multiplatform 1.10 发布:里程碑式更新!流星白龙4 小时前
【MySQL】19.MySQL用户管理匆忙拥挤repeat5 小时前
Android Compose 可组合项的生命周期、副作用APIhnlgzb6 小时前
目前编写安卓app的话有哪几种设计模式?studyForMokey7 小时前
【Android面试】Fragment生命周期专题Android系统攻城狮8 小时前
Android tinyalsa深度解析之pcm_plugin_open调用流程与实战(一百七十四)用户622386252178 小时前
Android 列表控件实战:从 ListView 到 RecyclerView,仿今日头条 HeadLine 项目全解析