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

问题描述 投票:1回答:1

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

但是,无论我尝试什么,该框始终会出现在左上角。

我尝试过:-获得LayoutParams作为MarginLayoutParams(它们是),并进行设置。将它们重新放置在视图中以进行良好测量。-上述链接中的所有答案

  • 使用TranslationX和-Y更改位置(可以工作,但是会遇到其他问题,例如状态栏可能并不总是24dp并似乎是hack)
                        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添加到不同的布局,这在所有情况下都会导致在该布局的左上角绘制方框

android kotlin android-view layoutparams
1个回答
0
投票

对于与我有相同问题的任何人: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
}
    
© www.soinside.com 2019 - 2024. All rights reserved.