0

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)
  • Try the following: 1) Add your views; 2) Create the _ConstraintSet_ and clone; 3) Constrain your views. Currently, your _ConstraintSet_ doesn't know about your views. – Cheticamp Jul 06 '23 at 14:46
  • Suppose I have 12 views, and I need to change their positions dynamically based on server data. I want to save and restore these positions using ConstraintSet. How can I achieve this?" – Nazirjon Kadirov Jul 07 '23 at 09:53
  • Isn't your comment a different question? – Cheticamp Jul 07 '23 at 12:43

1 Answers1

0

Constraint sets are used to set constraints on your views.

For more info: change constraints programmatically

But you can also change their position on the constraint layout. The following code creates 4 buttons aligned one by one on constraint layout:

val constLayout : ConstraintLayout = findViewById(R.id.constLayout)
    for (i in 0..3) {
        val newButton = Button(this)
        constLayout.addView(newButton)
        newButton.id = View.generateViewId()
        newButton.text = "im new"
        newButton.width = 75
        newButton.height = 75
        newButton.x = i*220f
        newButton.y = 0f
    }