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應用程序的新手,但是我編寫了一些應用程序,而無需在運行時添加視圖。希望這應該工作。我會盡快在家裏嘗試 –