androidviewandroid-linearlayoutandroid-constraintlayoutandroid-xml

How to adjust buttons properly inside LinearLayout if text on first button is more then half of screen


I am working on a layout file which have one parent LinearLayout and inside it two buttons and goal is to adjust buttons alignment according to the text size of buttons for an example if text size of any of button increase to half of the screen buttons should position them vertically otherwise should be show horizontally. Need help to fix this issue. Below is the layout file and its output that is tried so far.

xml:

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingVertical="0dp"
            android:text="I am long text to feed this button" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <Button
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="Test" />
    </LinearLayout>
</LinearLayout> 

Output:

enter image description here

Expected behaviour:

Scenario 1: If text size of any button is greater then half of screen.

enter image description here

Scenario 2: If text size is less then half of screen.

enter image description here


Solution

  • Found the solution so posting here too. Thanks @Cheticamp it works with androidx.constraintlayout.helper.widget.Flow in ConstraintLayout

    <androidx.constraintlayout.widget.ConstraintLayout>
    ....Other Views...
    
    <Button
        android:id="@+id/primary_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    
    <Button
        android:id="@+id/secondary_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    
    <androidx.constraintlayout.helper.widget.Flow
        android:id="@+id/flow1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
    app:constraint_referenced_ids="primary_button,secondary_button"
        app:flow_horizontalBias="0"
        app:flow_horizontalStyle="packed"
        app:flow_horizontalGap="5dp"
        app:flow_verticalBias="0"
        app:flow_wrapMode="chain"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textview" />
    </androidx.constraintlayout.widget.ConstraintLayout>