|
|
@@ -1,12 +1,56 @@
|
|
|
package com.aplid.calculation
|
|
|
|
|
|
import android.os.Bundle
|
|
|
+import android.view.MotionEvent
|
|
|
+import android.widget.LinearLayout
|
|
|
+import android.widget.TextView
|
|
|
import androidx.appcompat.app.AppCompatActivity
|
|
|
|
|
|
class MainActivity : AppCompatActivity() {
|
|
|
+
|
|
|
+ private lateinit var moveTextView : TextView
|
|
|
+
|
|
|
override fun onCreate(savedInstanceState: Bundle?) {
|
|
|
super.onCreate(savedInstanceState)
|
|
|
supportActionBar?.hide()
|
|
|
setContentView(R.layout.activity_main) // 绑定布局
|
|
|
+ moveTextView = findViewById(R.id.move)
|
|
|
+ }
|
|
|
+
|
|
|
+ // 处理触摸事件
|
|
|
+ override fun onTouchEvent(event: MotionEvent): Boolean {
|
|
|
+ when (event.action) {
|
|
|
+ MotionEvent.ACTION_DOWN -> {
|
|
|
+ // 触摸按下,记录触摸位置
|
|
|
+ moveTextView.isPressed = true
|
|
|
+ updatePosition(event)
|
|
|
+ return true // 消费事件
|
|
|
+ }
|
|
|
+ MotionEvent.ACTION_MOVE -> {
|
|
|
+ // 移动过程中更新位置
|
|
|
+ updatePosition(event)
|
|
|
+ return true // 消费事件
|
|
|
+ }
|
|
|
+ MotionEvent.ACTION_UP -> {
|
|
|
+ // 触摸抬起,结束操作
|
|
|
+ moveTextView.isPressed = false
|
|
|
+ return true // 消费事件
|
|
|
+ }
|
|
|
+ else -> return super.onTouchEvent(event)
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // 更新 TextView 的位置
|
|
|
+ private fun updatePosition(event: MotionEvent) {
|
|
|
+ val x = event.x.toInt()
|
|
|
+ val y = event.y.toInt()
|
|
|
+ moveTextView.text = "($x,$y)"
|
|
|
+ val params = moveTextView.layoutParams
|
|
|
+ if (params is LinearLayout.LayoutParams) {
|
|
|
+ params.leftMargin = x - (moveTextView.width / 2)
|
|
|
+ params.topMargin = y - (moveTextView.height / 2)
|
|
|
+ moveTextView.layoutParams = params
|
|
|
+ moveTextView.requestLayout() // 强制刷新布局
|
|
|
+ }
|
|
|
}
|
|
|
-}
|
|
|
+}
|