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
相关推荐
怪奇云呼军12 小时前
从声音特征到 CRM 回流:闪电智能 Voice Agent 沟通策略自适应系统 v1 实战哦哦~92114 小时前
北理工|Composites Part‑A 综述:纤维‑增强复合材料传统成型与增材制造全解析一笑的小酒馆15 小时前
Android视频直播播放器简单封装工会代表16 小时前
安卓手机搭建SOCKS5代理教程雨白16 小时前
Android AOP 切面编程实战:优雅地处理全局断网拦截huluang18 小时前
专业级安卓现场取证利器:拍照取证(PaiZaoXue),补齐行业取证工具核心短板奇特認18 小时前
MySQL集群技术 4.高可用之组复制 (MGR)阿pin18 小时前
Android随笔-SurfaceFlinger洋不写bug18 小时前
JavaComparable、Comparator、Cloneable接口解析,深拷贝浅拷贝详细解析小孔龙19 小时前
Android 应用间 UI 刷新与合成