Home > Software design >  How to set the width and height of a layout in Android?
How to set the width and height of a layout in Android?

Time:08-19

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?

CodePudding user response:

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.

  • Related