Search code examples
androidkotlinandroid-layouttextviewandroid-view

Expand two TextViews next to each other


I would like to put two TextViews next to each other and let both of them expand depending on their contents.

The contents of both TextViews are fully dynamic and unpredictable, therefore I want the solution to work consistently in all the cases shown in the image below:

  1. The first TextView's content is very long (and it may also turn out it must be wrapped into multiple lines), while the other TextView's content is relatively short.
  2. Exactly the opposite, i.e. the first TextView's content is shorter.
  3. Both TextViews' contents are long and must be wrapped. Ideally, they should meet in the middle.

expected layout

I tried various settings of LinearLayout, ConstraintLayout and RelativeLayout but none of them worked consistently in all the cases. To create the layout you can see in the screenshot above, I had to manually customize the attributes of each TextView depending on its text length. However, I presume I won't be able to easily judge how much space each text is going to take in runtime (e.g. whether it will be wrapped into multiple lines etc.), therefore I'm afraid I can't dynamically fine-tune the properties of the TextViews depending on their contents. That's why I'm trying to find some setting that would work consistently without my intervention, although I'm aware it may turn out it's impossible. Anyway, I hope I simply missed something obvious.

Alternatively, I would consider "measuring" the expected width of each text to make a decision regarding both TextViews' settings and fine-tune them dynamically, but only as a last resort.


Solution

  • You can try to achieve above result using Flexbox

    <?xml version="1.0" encoding="utf-8"?>
    <com.google.android.flexbox.FlexboxLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="8dp"
        app:flexDirection="row">
    
        <TextView
            android:id="@+id/textview1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            tools:text="@tools:sample/lorem/random" />
    
        <TextView
            android:id="@+id/textview2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            tools:text="@tools:sample/lorem/random" />
    
    </com.google.android.flexbox.FlexboxLayout>
    

    result: result of using Flexbox

    Take a look at all parameters that Flexbox provides to adjust to your needs. e.g. app:layout_minWidth which provides the min width for children.