Buttons in a RelativeLayout disappear after changing LayoutParams

Viewed 109

I have five buttons in a Relative layout, if I try to change their height dynamically, some buttons disappear.

How buttons are looking before clicking

Buttons after clicking

val w = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45f, resources.displayMetrics)
    btn_ran.setOnClickListener {
        btn_1.layoutParams = RelativeLayout.LayoutParams(w.toInt(), 700)
        btn_3.layoutParams = RelativeLayout.LayoutParams(w.toInt(), 700)
        btn_4.layoutParams = RelativeLayout.LayoutParams(w.toInt(), 700)
        btn_2.layoutParams = RelativeLayout.LayoutParams(w.toInt(), 700)
        btn_5.layoutParams = RelativeLayout.LayoutParams(w.toInt(), 700)

    }

All I want to do is to change all of the button's height randomly on the click of a button.

2 Answers

If You only want to change height to random value You can do it in this way:

button1.setOnClickListener {
    val h = (100..500).random() //random integer between 100 and 500
    button1.layoutParams.height = h
    button2.layoutParams.height = h
    button1.requestLayout() //refresh layout
}

I suspect that you are losing the relative positioning attributes when you create new LayoutParams objects. Remember that attributes like layout_toEndOf are part of the layout params.

Try this instead:

val w = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45f, resources.displayMetrics)
btn_ran.setOnClickListener {
    btn_1.updateLayoutParams { this.width = w }
    btn_3.updateLayoutParams { this.width = w }
    btn_4.updateLayoutParams { this.width = w }
    btn_2.updateLayoutParams { this.width = w }
    btn_5.updateLayoutParams { this.width = w }
}

This makes use of the updateLayoutParams extension function that is part of the Core KTX library. It will keep everything about the LayoutParams the same, but also allow you to modify the width.

If you can't use Core KTX, then you can be a little more verbose. Replace each of those calls with something like this:

val params1 = btn_1.layoutParams
params1.width = w
btn_1.layoutParams = params1
Related