Programmatically change Button Constraints settings and fill space

android android-constraintlayout

763 观看

1回复

10 作者的声誉

I am developing App in Android and now I have problem with buttons align. I need to dynamically set constraints ( I have 3 cases of buttons alignment), I have a 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>

As you can see it contains two buttons, now programmatically i need to set their alignment, for example in one line first next to second. I am doing it with this code:

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

Now it looks like this: image, but I want to achieve that the first one adjust his width to fill part on the left and second one space on the right. I have tried combinations of layout_width, set every connects etc. but still without success.

Thanks in advance for help.

作者: P. Grzanka 的来源 发布者: 2017 年 12 月 27 日

回应 1


0

118 作者的声誉

决定

Have you tried using

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

You should also check out the ConstraintSet documentation here.

作者: Ian White 发布者: 2017 年 12 月 27 日
32x32