【问题标题】:Programmatically change Button Constraints settings and fill space以编程方式更改按钮约束设置和填充空间
【发布时间】:2017-12-28 00:45:19
【问题描述】:

我正在 Android 中开发应用程序,现在我遇到了按钮对齐问题。我需要动态设置约束(我有 3 种按钮对齐情况),我有一个 ConstraintLayout:

<android.support.constraint.ConstraintLayout
    android:id="@+id/bottomLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/border"
    android:padding="3dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/middleLayoutText"
    app:layout_constraintVertical_chainStyle="packed" >

    <Button
        android:id="@+id/firstButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/secondButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</android.support.constraint.ConstraintLayout>

如您所见,它包含两个按钮,现在我需要以编程方式设置它们的对齐方式,例如在一行中的第一行和第二行。我正在使用以下代码:

ConstraintLayout layout = (ConstraintLayout) constraintLayout.findViewById(R.id.bottomLayout);
ConstraintSet set = new ConstraintSet();
set.clone(layout);

Button firstButton = (Button) layout.findViewById(R.id.firstButton);
firstButton.setText(buttonsOption.getFirstButton().getContent().getText());

Button secondButton =  (Button) layout.findViewById(R.id.secondButton);
secondButton.setText(buttonsOption.getSecondButton().getContent().getText());

set.connect(firstButton.getId(), ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT);
set.connect(firstButton.getId(), ConstraintSet.RIGHT, secondButton.getId(), ConstraintSet.LEFT);
set.connect(secondButton.getId(), ConstraintSet.START, firstButton.getId(), ConstraintSet.END);
set.connect(secondButton.getId(), ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END);
set.setHorizontalChainStyle(firstButton.getId(),ConstraintSet.CHAIN_PACKED);
set.setHorizontalChainStyle(secondButton.getId(),ConstraintSet.CHAIN_PACKED);
set.applyTo(layout); 

现在看起来像这样:image,但我想实现第一个调整他的宽度以填充左侧的部分和右侧的第二个空间。我尝试了 layout_width 的组合,设置了每个连接等,但仍然没有成功。

提前感谢您的帮助。

【问题讨论】:

    标签: android android-constraintlayout


    【解决方案1】:

    您是否尝试过使用

    set.constrainWidth(firstButton.getId(), ConstraintSet.MATCH_CONSTRAINT);
    set.constrainWidth(secondButton.getId(), ConstraintSet.MATCH_CONSTRAINT);
    

    您还应该查看 ConstraintSet 文档here

    【讨论】:

    • 谢谢!我已经读过它,但我忘了检查它......效果很好:D
    猜你喜欢
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多