2

I have already spent some time finding solution for this problem.

In onCreate method of activity, I create two Buttons and set their constraints. But when done this in xml the same constraints look different.

XML: XML constraints image

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:text="Button 1"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginTop="8dp"
    android:text="Button 2"
    app:layout_constraintLeft_toRightOf="@+id/button"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

Programmaticaly: Programmatic constraints image

    Button btn1 = new Button(this);
    Button btn2 = new Button(this);
    btn1.setText("Button 1");
    btn2.setText("Button 2");

    layout.addView(btn1);
    layout.addView(btn2);

    ConstraintSet set = new ConstraintSet();
    set.clone(layout);

    set.connect(btn1.getId(), ConstraintSet.LEFT, layout.getId(), ConstraintSet.LEFT, 8);
    set.connect(btn1.getId(), ConstraintSet.TOP, layout.getId(), ConstraintSet.TOP, 8);
    set.connect(btn2.getId(), ConstraintSet.LEFT, btn1.getId(), ConstraintSet.RIGHT, 8);
    set.connect(btn2.getId(), ConstraintSet.TOP, layout.getId(), ConstraintSet.TOP, 8);
    set.connect(btn2.getId(), ConstraintSet.RIGHT, layout.getId(), ConstraintSet.RIGHT, 8);
    set.applyTo(layout);

I have read this Programmatically connecting multiple views set to any size using ConstraintLayout but that was just wrong connection and I don't see anything wrong in my connections, checked it multiple times.

1 Answers1

1

The problem is for both the button you didn't set any id, so it's taken default view id View.NO_ID, So if you change id for the button it will work fine.

Try, to add the id to the button1 like the below sample, it will work as you expected.

btn1.setId(View.generateViewId());
Muthukrishnan Rajendran
  • 11,122
  • 3
  • 31
  • 41
  • thx, I am new to programming android apps, but I have programmed some apps without adding views at runtime. hope this should work. I will try it as soon as i'll be at home – Martin Bodický Jun 17 '17 at 13:32