无需用到悬浮窗权限
1.布局:只需要在xml里面按照普通的写法,摆放位置一般写在未拖动前的默认位置。
2.方法
private fun initFloatView(){
val temp = intArrayOf(0, 0)
var isDrag = false
var clickTime:Long = 0
var downX=0
var downY=0
floatView.setOnTouchListener { view, event ->
val eventAction: Int = event.action
val x = event.rawX.toInt() // 记录下动作相对于原点的x坐标
val y = event.rawY.toInt() // 记录下动作相对于原点的y坐标
when (eventAction) {
MotionEvent.ACTION_DOWN -> {
isDrag = false
temp[0] = event.x.toInt()
temp[1] = y - view.top
downX=event.x.toInt()
downY=event.y.toInt()
}
MotionEvent.ACTION_MOVE -> {
//isDrag = true
view.layout(
x - temp[0],
y - temp[1],
x + view.width - temp[0],
y - temp[1] + view.height
)
//解决某些曲面屏手机,点击时走滑动手势,导致isDrag = true
val moveX=event.x.toInt()
val moveY=event.y.toInt()
val offsetX=Math.abs(downX-moveX)
val offsetY=Math.abs(downY-moveY)
if(offsetX>1||offsetY>1){
isDrag = true
}
view.postInvalidate()
}
MotionEvent.ACTION_UP -> {
val layoutParams = ConstraintLayout.LayoutParams(
ScreenUtil.dp2px(this,56f),
ScreenUtil.dp2px(this,65f)
)
layoutParams.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
layoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
layoutParams.leftMargin = view.left
layoutParams.topMargin = view.top
layoutParams.setMargins(view.left, view.top, 0, 0)
view.layoutParams = layoutParams
if (!isDrag){
//点击事件处理实现
}
}
}
true
}
}