要移动的View XML布局:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="60dp"
android:layout_height="60dp"
android:background="@android:color/holo_blue_bright">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Main" />
</FrameLayout>
把这个View放到父容器里,用于判断手指位置:
package com.example.fingermoveview
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout
import com.example.fingermoveview.databinding.ViewMoveBinding
/**
* 自由移动的view
* @author du_xi
* Created at 2024/4/22
*/
class MoveView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr), View.OnTouchListener {
private val viewBinding = ViewMoveBinding.inflate(LayoutInflater.from(context), this, true)
init {
setOnTouchListener(this)
}
private var downPoint = floatArrayOf(0f, 0f)
private var trans = floatArrayOf(0f, 0f)
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
when (event?.action) {
MotionEvent.ACTION_DOWN -> {
val inArea =
event.x > viewBinding.root.x && event.x < viewBinding.root.x + viewBinding.root.width && event.y > viewBinding.root.y && event.y < viewBinding.root.y + viewBinding.root.height
if (inArea) {
downPoint = floatArrayOf(event.x, event.y)
trans =
floatArrayOf(viewBinding.root.translationX, viewBinding.root.translationY)
return true
}
}
MotionEvent.ACTION_MOVE -> {
if (event.x == downPoint[0] && event.y == downPoint[1]) {
return true
}
viewBinding.root.translationY = trans[1] + event.y - downPoint[1]
viewBinding.root.translationX = trans[0] + event.x - downPoint[0]
return true
}
MotionEvent.ACTION_UP -> {
downPoint = floatArrayOf(0f, 0f)
}
}
return false
}
}
使用方法:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.example.fingermoveview.MoveView
android:id="@+id/move_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>