2
我已经花了一些时间为这个问题寻找解决方案。Android的编程和XML约束不同
在onCreate活动方法中,我创建两个Button并设置它们的约束。但是当在xml中完成时,相同的约束看起来不同。
<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);
我已阅读本Programmatically connecting multiple views set to any size using ConstraintLayout但这是不对的连接,我没有看到任何错误的,我连接,检查它的多个倍。
thx,我是编程android应用程序的新手,但是我编写了一些应用程序,而无需在运行时添加视图。希望这应该工作。我会尽快在家里尝试 –