Skip to content
Advertisement

How to set the width and height of a layout in Android?

I have this ConstraintLayout:

lateinit var myConstraintLayout: ConstraintLayout

I try to set its width and height to match its parent via code, like this:

       val params = ConstraintLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        myConstraintLayout.setLayoutParams(params)

But I get error androidx.constraintlayout.widget.ConstraintLayout$LayoutParams cannot be cast to android.widget.FrameLayout$LayoutParams Why? How do I fix this?

Advertisement

Answer

The LayoutParams need to be the LayoutParams type of the parent ViewGroup. It is the parent ViewGroup that actually uses these params, after all. In this case, the parent of your ConstraintLayout is apparently a FrameLayout, so you need to use FrameLayout.LayoutParams.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement