【发布时间】:2021-09-07 16:43:27
【问题描述】:
我有一个应用程序。现在,当我点击屏幕上的任意位置时,该应用程序会执行此操作,它会在触摸点显示一个 ImageView。这在MotionEvent.ACTION_DOWN 中有所体现。
我希望应用程序执行以下操作:只要我用手指触摸屏幕并移动它,ImageView 就会跟随我的手指线。如何在MotionEvent.ACTION_MOVE 中实现这一点?
这里是activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/relative_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
</RelativeLayout>
这里是 MainActivity.kt :
class MainActivity : AppCompatActivity() {
@SuppressLint("ClickableViewAccessibility", "UseCompatLoadingForDrawables")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val rr = findViewById<View>(R.id.relative_layout) as RelativeLayout
rr.setOnTouchListener { v, event ->
if (event.action == MotionEvent.ACTION_DOWN) {
val x = event.x.toInt()
val y = event.y.toInt()
val lp = RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
)
val iv = ImageView(applicationContext)
lp.setMargins(x, y, 0, 0)
iv.layoutParams = lp
iv.setImageDrawable(
resources.getDrawable(
R.drawable.ic_baseline_blur_circular_24
)
)
(v as ViewGroup).addView(iv)
}
if (event.action == MotionEvent.ACTION_MOVE) {
// what should i do here to move the ImageView follow my finger?
}
false
}
}
}
当我在任何地方触摸屏幕时:
【问题讨论】:
标签: android kotlin touch screen motionevent