如何在ConstraintLayout中设置视图的绝对位置

3

当我使用getLocationOnScreengetLocationInWindow时,我会得到视图的绝对坐标。令我惊讶的是,视图的y坐标考虑了手机的状态栏,这意味着如果视图位于屏幕顶部,其y坐标不会设置为0。

profilePic1.getLocationOnScreen(imagePosition1.coor)

另一方面,使用 view.xview.y 设置视图的位置并不是绝对的,而是相对于布局的,这意味着:

profilePic1.y = imagePosition1.coor[1]

该图像将被放置在完全不同的位置,因为它将添加状态栏的高度到新位置。

我的问题是:是否可以在ConstraintLayout中设置视图的坐标,而不是相对方式?我找到了一个涉及相对布局的讨论。

另一个选项:是否可能获取布局的相对坐标,而不是绝对坐标(如getLocationOnScreen所示)?

我的问题是,我获取布局内部视图的位置,并且无法使用此信息来重新定位这些视图。

2个回答

2

抱歉,我的错。答案很简单,只需要使用:

view.top
view.left

为了获取布局内的相对位置。我希望不要删除这个问题,也许其他人可以从中受益,展示屏幕绝对位置和布局内相对位置之间的差异。

0
有没有可能在 ConstraintLayout 中以绝对方式设置视图的坐标?
在 ConstraintLayout 中定位视图应该使用约束,因为 layout_editor_absolutex|y 仅用于设计目的。
但是这里有几种在 ConstraintLayout 中将视图定位到绝对位置的方法:
1. 将视图的 topMargin 和 leftMargin 设置为绝对位置。
val view = findViewById<...>

val params = view.layoutParams as ConstraintLayout.LayoutParams
params.leftMargin = x // absolute x position
params.topMargin = y // absolute y position
view.requestLayout()
  • 创建水平和垂直参考线,并将它们的边缘分别设置为y、x绝对位置;然后将视图约束到参考线上。
val view = findViewById<...>

// Create a horizontal & vertical guidelines and add them to the constraintLayout.
val verticalGL = getGuideline(this, ConstraintLayout.LayoutParams.VERTICAL)
val horizontalGL = getGuideline(this, ConstraintLayout.LayoutParams.HORIZONTAL)
constraintLayout.addView(verticalGL)
constraintLayout.addView(horizontalGL)

// Set the position of the guidelines.
verticalGL.setGuidelineBegin(x) // absolute x position
horizontalGL.setGuidelineBegin(y) // absolute y position

val set = ConstraintSet()
// Clone the layout's ConstraintSet.
set.clone(constraintLayout)
// Constraint the button to the guideline and apply to the ConstraintSet.
set.connect(view.id, ConstraintSet.START, verticalGL.id, ConstraintSet.START)
set.connect(view.id, ConstraintSet.TOP, horizontalGL.id, ConstraintSet.TOP)
set.applyTo(constraintLayout)


private fun getGuideline(context: Context, orientation: Int): Guideline {
    val guideline = Guideline(context)
    guideline.id = Guideline.generateViewId()
    val lp = ConstraintLayout.LayoutParams(
        ConstraintLayout.LayoutParams.WRAP_CONTENT,
        ConstraintLayout.LayoutParams.WRAP_CONTENT
    )
    lp.orientation = orientation
    guideline.layoutParams = lp
    return guideline
}


我假设您想要定位的视图没有任何限制。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接