Home > front end >  Constraints are ignored for programmatically added buttons in the constraint layout - Android
Constraints are ignored for programmatically added buttons in the constraint layout - Android

Time:11-10

I am creating a custom layout, based on ConstraintLayout, in which I would like to populate multiple buttons programmatically around the button (Button Main) using

Below is the code for my layout:

class MyCustomLayout(context: Context, attrs: AttributeSet) : ConstraintLayout(context, attrs) {

init {
    val layout = inflate(context, R.layout.circular_buttons, this) as ConstraintLayout
    val buttonMain = findViewById<Button>(R.id.circular_buttons_button_main)
    val newButton = Button(context)
    newButton.id = View.generateViewId()
    newButton.text = "Button Kotlin"
    newButton.visibility = VISIBLE
    val params =
        LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
        ).apply {
            circleConstraint = buttonMain.id
            circleRadius = 100
            circleAngle = 60f
        }
    newButton.layoutParams = params
    layout.addView(newButton)
}}

I also tried adding constraints with the ConstraintSet, however, results are the same.

val constraintSet = ConstraintSet()
constraintSet.clone(layout)
constraintSet.constrainCircle(newButton.id, buttonMain.id, 100,  60f)
constraintSet.constrainHeight(newButton.id, ConstraintSet.WRAP_CONTENT)
constraintSet.constrainWidth(newButton.id, ConstraintSet.WRAP_CONTENT)
constraintSet.applyTo(layout)

What am I doing wrong?

CodePudding user response:

You are adding the your button to a different parent. Your 'layout' variable is referenced to parent view. The ConstraintLayout you wanted to add a button to became a child of this view.

Your hierarchy was something like this:

<ConstraintLayout>
  <ConstraintLayout>
    <Button> --> Added from XML
  <ConstraintLayout>
  <Button> --> Added from code 
</ConstraintLayout>

To solve this you need to take the reference of the constraint layout in XML and add button to it.

For example:

val clMain = layout.findViewById<ConstraintLayout>(R.id.cl_main)
...
clMain.addView(newButton)
  • Related