本文首发于公众号“AntDream”,欢迎微信搜索“AntDream”或扫描文章底部二维码关注,和我一起每天进步一点点

Android经典实战之如何获取View和ViewGroup的中心点_android


在 Android 中,要获取 ViewViewGroup 的中心点(即中心坐标),可以通过以下步骤完成。

获取 View 中心点

View 的中心点可以通过获取其左上角坐标和宽高计算得出。

val view = findViewById<View>(R.id.your_view_id)

// 获取 View 的左上角位置
val x = view.left
val y = view.top

// 获取 View 的宽度和高度
val width = view.width
val height = view.height

// 计算中心点
val centerX = x + width / 2
val centerY = y + height / 2

println("View Center: ($centerX, $centerY)")

获取 ViewGroup 中心点

ViewGroup 也是一种 View,所以获取中心点的方法与 View 类似。

val viewGroup = findViewById<ViewGroup>(R.id.your_viewgroup_id)

// 获取 ViewGroup 的左上角位置
val x = viewGroup.left
val y = viewGroup.top

// 获取 ViewGroup 的宽度和高度
val width = viewGroup.width
val height = viewGroup.height

// 计算中心点
val centerX = x + width / 2
val centerY = y + height / 2

println("ViewGroup Center: ($centerX, $centerY)")

注意事项

1、 View 的测量过程:如果你在 onCreateonViewCreated 方法中立即获取视图中心点,这时视图可能尚未完成测量,宽高可能为 0。为了确保视图已经完成测量,可以使用 ViewTreeObserver.OnGlobalLayoutListenerpost 方法。

val view = findViewById<View>(R.id.your_view_id)

 view.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
     override fun onGlobalLayout() {
         view.viewTreeObserver.removeOnGlobalLayoutListener(this)

         // 获取中心点
         val centerX = view.left + view.width / 2
         val centerY = view.top + view.height / 2

         println("View Center: ($centerX, $centerY)")
     }
 })

或者

val view = findViewById<View>(R.id.your_view_id)

 view.post {
     // 获取中心点
     val centerX = view.left + view.width / 2
     val centerY = view.top + view.height / 2

     println("View Center: ($centerX, $centerY)")
 }

2、 绝对坐标和相对坐标:上述方法获取的是相对于父容器的坐标。如果你需要屏幕上的绝对坐标,可以使用 getLocationOnScreengetLocationInWindow 方法。

val view = findViewById<View>(R.id.your_view_id)
 val location = IntArray(2)

 // 获取屏幕上的绝对位置
 view.getLocationOnScreen(location)
 val x = location[0]
 val y = location[1]

 // 计算中心点
 val centerX = x + view.width / 2
 val centerY = y + view.height / 2

 println("Absolute View Center: ($centerX, $centerY)")

通过这些方法,你可以准确获取 ViewViewGroup 的中心点,从而进行后续计算或操作。


欢迎关注我的公众号AntDream查看更多精彩文章!