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

OnTouch giving different position, compared to ImageView position

我以编程方式定义了很多 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...

但是我的触摸没有被识别。 我也尝试过,不是在每个 ImageView 中添加 onTouchListener,而是在主视图中添加 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 倍,我可以缩放 in/out 和滚动,但我没有使用 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/test: 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(实际 phone 宽度),而不是 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.

更新: 添加到 XML ZoomLayout 属性 app:hasClickableChildren="true" 修复问题。