FlexBoxLayout - How to stretch buttons only when wrapped?

42 Views Asked by At

I am trying to implement a view of two buttons that will behave one way when there's room for the buttons to be rendered next to each other, and in another way when there isn't.

Here are the requirements:

When buttons are short enough:

  • Buttons should appear with space between them.
  • Button size should wrap the text.
  • Negative button should be on the left, positive on the right.

When one of the button's text is too long:

  • Buttons should be one on top of the other.
  • Button size fill the entire width.
  • Positive button should be on top of the negative button.

Here's an illustration of the expected layout:

enter image description here

Here's my code so far:

<com.google.android.flexbox.FlexboxLayout
    android:id="@+id/buttons"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:flexDirection="row"
    app:flexWrap="wrap_reverse"
    app:alignItems="center">

  <com.google.android.material.button.MaterialButton
      android:id="@+id/negative_btn"
      style="@style/OutlinedButton"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"/>

  <com.google.android.material.button.MaterialButton
      android:id="@+id/positive_btn"
      style="@style/TonalButton"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
</com.google.android.flexbox.FlexboxLayout>

enter image description here

So my question is, how can I make the bottom button look like the expected Case B?

Thanks!

1

There are 1 best solutions below

1
miral On

Add a below line in each button and it will grow to match parent

app:layout_flexGrow="1.0"

<com.google.android.flexbox.FlexboxLayout
            android:id="@+id/buttons"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:flexDirection="row"
            app:justifyContent="center"
            app:layout_constraintTop_toTopOf="parent"
            app:flexWrap="wrap_reverse"
            app:alignItems="center">

            <com.google.android.material.button.MaterialButton
                android:id="@+id/negative_btn"
                android:textFontWeight="1"
                android:text="first here is my version of thenbbhefbhfbhjefbhjfbhf "
                app:layout_flexGrow="1.0"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>

            <com.google.android.material.button.MaterialButton
                android:id="@+id/positive_btn"
                android:text="second"
                android:textFontWeight="1"
                app:layout_flexGrow="1.0"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </com.google.android.flexbox.FlexboxLayout>