我通过编程定义了许多ImageView
,它们在数组中的位置如下:
const1Positions = arrayOf(
Point(dpToPx(349), dpToPx(258)),
Point(dpToPx(491), dpToPx(302)),
Point(dpToPx(495), dpToPx(429)),
Point(dpToPx(669), dpToPx(524)),
Point(dpToPx(600), dpToPx(618))
)
这是
dpToPx
:fun Activity.dpToPx(dp: Int): Int {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp.toFloat(),
resources.displayMetrics
).roundToInt()
}
我正在尝试将
setOnTouchListener
编码为每个ImageView
(当我在for中初始化它们时,我也称为imageview.setOnTouchListener...
)但是我的触摸无法识别。
我也尝试过,而不是在每个
onTouchListener
中添加ImageView
,而不是在主 View 中添加onTouchEvent
,并且如果event.x == imageview.x
(用户触摸了ImageView
),请执行操作。但是event.x
和image.x
不同。这是我的
setOnTouchListener
:view.setOnTouchListener { v, event ->
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
Log.d("DEBUG_TAG", event.x.toString())
true
}
MotionEvent.ACTION_UP -> {
Log.d("DEBUG_TAG", "Action was UP")
Log.d("test", const1Positions[0].x.toString())
Log.d("test2", view.width.toString())
true
}
MotionEvent.ACTION_MOVE -> {
Log.d("DEBUG_TAG", "Action was MOVE")
true
}
MotionEvent.ACTION_CANCEL -> {
Log.d("DEBUG_TAG", "Action was CANCEL")
true
}
MotionEvent.ACTION_OUTSIDE -> {
Log.d(
"DEBUG_TAG",
"Movement occurred outside bounds of current screen element"
)
true
}
else -> super.onTouchEvent(event)
}
}
我的布局宽度和高度都比屏幕大2倍,可以放大/缩小和滚动,但我没有使用
ScrollView
。我正在使用GitHub上的自定义布局。params.width = view.resources.displayMetrics.widthPixels * 2
params.height = view.resources.displayMetrics.heightPixels * 2
view.layoutParams = params
我正在使用
Log
比较触摸位置,ImageView
位置和布局大小。但是结果却完全不同:2020-03-25 19:31:07.796 26112-26112 / com.example.android.bonte_android D / DEBUG_TAG:395.63367
2020-03-25 19:31:07.833 26112-26112 / com.example.android.bonte_android D /测试:890
2020-03-25 19:31:07.834 26112-26112 / com.example.android.bonte_android D / test2:2160
屏幕位置基于2160,所以它显示为890。但是即使我在屏幕上触摸,
event.x
位置也会显示395而不是890,并且event.x
接收到的最大位置是1080(实际电话宽度),而不是2160 (布局的最大宽度)。有谁知道为什么会这样吗?与其将
onTouchListener
添加到View
,不如将其添加到所有ImageView
中,最好,但是正如我所说的,onTouchListener
无法识别任何触摸,
最佳答案
希望this答案(由Piyush撰写)会令您满意:
MotionEvent will sometimes return absolute X and Y coordinates relative to the view, and sometimes relative coordinates to the previous motion event.
getRawX() and getRawY() that is guaranteed to return absolute coordinates, relative to the device screen.
While getX() and getY(), should return you coordinates, relative to the View, that dispatched them.
UPD:在XML属性
ZoomLayout
中将添加到 app:hasClickableChildren="true"
中解决了该问题。
关于java - 与ImageView位置相比,OnTouch给出了不同的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60858599/