为什么我的 LayoutParams 不会改变我的布局?

Why won't my LayoutParams change my layout?

我想在 EditText 旁边显示一个带有建议条目的框。 我认为我必须设置 LayoutParams(如 this question.

中的建议

但是,无论我怎样尝试,框总是出现在左上角。

我尝试了什么: - 获取 LayoutParams 作为 MarginLayoutParams(它们是),并设置它们。将它们放回视图中以备不时之需。 - 上述link中的所有答案

                        val layoutParams = box?.layoutParams
                        //val layoutParams = ConstraintLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT).apply{
                        //    setMargins(left, top, 0,0)
                        //}
                        if (layoutParams !is ViewGroup.MarginLayoutParams) return@onTextChanged

                        //layoutParams.leftMargin = left
                        layoutParams.marginStart = left
                        layoutParams.topMargin = top
                        box?.layoutParams = layoutParams // Don't think this is necessary 
                        Log.d(TAG, "$layoutParams")

                        // works, but don't like it
                        // box?.translationX = left.toFloat()
                        // box?.translationY = top.toFloat()

                        //doesn't work
                        //box?.setMargins(left, top, right, 1000)

函数View.Setmargins如下:

fun View.setMargins(left: Int, top: Int, right: Int, bottom: Int) {
    if (layoutParams is MarginLayoutParams) {
        val p = layoutParams as MarginLayoutParams
        p.setMargins(left, top, right, bottom)
        requestLayout()
    }
}

我想做的事情的完整来源here(上面的片段在第 170 行,对其进行了一些编辑以显示我尝试过的事情)

我尝试过的其他事情:将 box 添加到不同的布局,这在所有情况下都会导致在该布局的左上角绘制框

对于和我有同样问题的人: Mike M. 将 LayoutParams 设为 ConstraintLayout.LayoutParams 并将其 topToTopstartToStart 字段设置为 ConstraintLayout.LayoutParams.PARENT_ID 的建议起到了作用,即。

(box?.layoutParams as ConstraintLayout.LayoutParams).apply{
    topToTop = ConstraintLayout.LayoutParams.PARENT_ID
    startToStart = ConstraintLayout.LayoutParams.PARENT_ID
    topMargin = top
    marginStart = left
}