OnTouch giving different position, compared to ImageView position
我有许多以编程方式定义的
1 2 3 4 5 6 7 |
这里是
1 2 3 4 5 6 7 | fun Activity.dpToPx(dp: Int): Int { return TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, dp.toFloat(), resources.displayMetrics ).roundToInt() } |
我试图
但我的触摸无法识别。
我也尝试过,而不是向每个
这是我的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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 倍,我可以放大/缩小和滚动,但我没有使用
1 2 3 | params.width = view.resources.displayMetrics.widthPixels * 2 params.height = view.resources.displayMetrics.heightPixels * 2 view.layoutParams = params |
我使用
1 2 3 | 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。但是即使我触摸屏幕,
而不是将
我希望这个答案(由 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 属性