gpt4 book ai didi

java - 与ImageView位置相比,OnTouch给出了不同的位置

转载 作者:行者123 更新时间:2023-12-02 13:43:54 25 4
gpt4 key购买 nike

我通过编程定义了许多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.ximage.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com