I'm trying to programmatically add two buttons to a ConstraintLayout and change their positions. I know how to add a single view, but I'm having trouble figuring out how to add multiple views and modify their positions.
Is there a way to programmatically add multiple views (buttons) to a ConstraintLayout? And how can I change their positions, such as aligning them to the left, right, or center of the ConstraintLayout?
I would appreciate any help or code examples!
val layout = findViewById<ConstraintLayout>(R.id.activity_main)
val set = ConstraintSet()
set.clone(layout)
// Button 1:
val button = Button(this)
button.text = "Hello"
button.id = View.generateViewId()
layout.addView(button)
set.connect(button.id, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, 0)
set.connect(button.id, ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, 0)
set.connect(button.id, ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT, 0)
set.constrainHeight(button.id, 200)
set.applyTo(layout)
// Button 2:
val newButton = Button(this)
newButton.text = "Yeeey"
newButton.id = View.generateViewId() // Generate a unique ID for the new button
layout.addView(newButton)
set.connect(newButton.id, ConstraintSet.BOTTOM, button.id, ConstraintSet.TOP, 0)
set.connect(newButton.id, ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, 0)
set.connect(newButton.id, ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT, 0)
set.constrainHeight(newButton.id, 200)
set.applyTo(layout)