Search code examples
androidkotlinandroid-viewlayoutparams

Why won't my LayoutParams change my layout?


I want to display a box with suggested entries next to an EditText. I figured I'd have to set LayoutParams (like suggested in this question.

However, no matter what I try, the box always ends up in the top left corner.

What I tried: - get LayoutParams as MarginLayoutParams (which they are), and set them. Set them back in the view for good measure. - All the answers in the link mentioned above

  • Change the position with TranslationX and -Y (which works, but runs into other problems like status bar might not always be 24dp and seems a 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)

the function View.Setmargins is as follows:

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()
    }
}

Complete source of the thing I want to do here (snippet above is at line 170, edited it a bit to show things I've tried)

Other things I have tried: add box to different layouts, which in all cases results in the box being drawn in the top-left corner of that layout


Solution

  • For anybody having the same problem as I had: Mike M. 's suggestion to get the LayoutParams as ConstraintLayout.LayoutParams, and also set its topToTop and startToStart fields to ConstraintLayout.LayoutParams.PARENT_ID did the trick, ie.

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