- 获取手指触摸点的坐标
binding.view.setOnTouchListener { _, motionEvent ->
if(motionEvent.action == MotionEvent.ACTION_MOVE) {
binding.textShow.text = "x: " + motionEvent.x + " ,y: " + motionEvent.y
}
return@setOnTouchListener true
}
- 获取设备的分辨率
binding.textDevice.text =
"heightPixels: " + resources.displayMetrics.heightPixels + " , widthPixels: " + resources.displayMetrics.widthPixels +
" ,densityDpi: " + resources.displayMetrics.densityDpi + " ,densityDpi: " + resources.displayMetrics.density +
" ,scaledDensity: " + resources.displayMetrics.scaledDensity
heightPixels: 1920 , widthPixels: 1080 ,densityDpi: 480 ,densityDpi: 3.0 ,scaledDensity: 3.0
- How to get the absolute coordinates of a view in Android?
如何获取控件的绝对坐标?
var location = IntArray(2)
binding.imageView2.getLocationOnScreen(location)
binding.textDevice.text = "location[0]: " + location[0] + ", location[1]: " + location[1]
要延时获取,在onCreate获取到的数据均为0 location[0]: 360, location[1]: 773 图片所在的左上角的绝对坐标值
可以创建个通用的接口
fun getLocationOnScreen(view: View): Point {
val location = IntArray(2)
view.getLocationOnScreen(location)
return Point(location[0], location[1])
}
- 代码中获取控件的宽高,结果是px像素值
var rect = Rect()
binding.homeTop.getLocalVisibleRect(rect)
binding.textDevice.text = "bottom: " + rect.bottom + ", top: " + rect.top + ", left: " + rect.left +
", right: " + rect.right + ", height: " + rect.height() + ", width: " + rect.width()
图片分辨率为120x91px,放在drawable目录下,且要延时获取,在onCreate获取到的数据均为0 getGlobalVisibleRect: rect.bottom: 1278, top: 228, height: 1050, left: 0, right: 1080, width: 1080 getLocalVisibleRect: rect.bottom: 1050, top: 0, height: 1050, left: 0, right: 1080, width: 1080
注意: 以上方法在OnCreate方法中调用,都会返回0,这是因为View还未加载完毕. 建议在onWindowFocusChanged方法中进行获取,有些情况下onWindowFocusChanged不好用的时候(比如ActivityGroup),可以这样写:
binding.fragmentHomeTop.homeTop.post {
initSystem()
initBehavior()
}
参考链接: android 获取控件的宽高和view的位置
|