Android 程序化和 XML 约束是不同的



我已经花了一些时间寻找这个问题的解决方案。

在 onCreate 活动方法中,我创建了两个按钮并设置它们的约束。但是,在 xml 中执行此操作时,相同的约束看起来会有所不同。

XML: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" />
编程

方式:编程约束图像

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

我已经阅读了使用 ConstraintLayout 以编程方式连接设置为任何大小的多个视图,但这只是错误的连接,我在连接中没有看到任何错误,多次检查它。

问题是对于您没有设置任何id的两个按钮,因此它采用默认视图id View.NO_ID,因此如果您更改按钮的id,它将正常工作。

尝试将 id 添加到 button1 中,如以下示例所示,它将按预期工作。

btn1.setId(View.generateViewId());

最新更新