2

我已经花了一些时间为这个问题寻找解决方案。Android的编程和XML约束不同

在onCreate活动方法中,我创建两个Button并设置它们的约束。但是当在xml中完成时,相同的约束看起来不同。

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); 

我已阅读本Programmatically connecting multiple views set to any size using ConstraintLayout但这是不对的连接,我没有看到任何错误的,我连接,检查它的多个倍。

回答

1

问题是你没有设置任何id的按钮,所以它采用默认视图ID View.NO_ID,所以如果你改变按钮的ID它会正常工作。

尝试将id添加到按钮1,就像下面的示例一样,它将按照您的预期工作。

btn1.setId(View.generateViewId()); 
+0

thx,我是编程android应用程序的新手,但是我编写了一些应用程序,而无需在运行时添加视图。希望这应该工作。我会尽快在家里尝试 –