我正在在Android中开发应用程序,现在我对按钮对齐有问题。我需要动态设置约束(我有3个按钮对齐情况),我有一个约束layout:
<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);
现在看起来像这样:图像,但是我想实现第一个调整他的宽度,以填充右侧和第二个空间。我尝试了Layout_width的组合,设置每个连接等。但是仍然没有成功。
事先感谢您的帮助。
您是否尝试过使用
set.constrainWidth(firstButton.getId(), ConstraintSet.MATCH_CONSTRAINT);
set.constrainWidth(secondButton.getId(), ConstraintSet.MATCH_CONSTRAINT);
您还应该在此处查看"约束"文档。