androidlayoutandroid-linearlayout

Divide space in LinearLayout depending on contents


I'd like to make myself a ListView with rows showing the name and the price of some product horizontally aligned.

I want to the price to get the width it needs and the name to wrap to a new line if width is running out.

So I used a horizontal LinearLayout, but name and price were overlapping. So I tried this LinearLayout space distribution solution but that way name and price are both wrapped.

Is there a way to have a 'take what you need' + 'take whats left' distriubtion?


Solution

  • LinearLayout is good when you know, how exactly you want to divide the space, either in a ratio or equally.

    The described layout can better be achieved using RelativeLayout.

    NOTE : You may want to use minWidth attribute to your name TextView, so that if price text becomes lengthy enough to cover whole width, name TextView is not pushed out of screen.

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@id/price"
            android:minWidth="100dp"
            android:text="Name extra text goes to next line"
            android:textColor="@color/black"
            android:textSize="28sp" />
    
        <TextView
            android:id="@+id/price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:text="Long Price Text Text"
            android:textColor="@color/black"
            android:textSize="28sp" />
    </RelativeLayout>
    

    Sample Outputs:

    Output1 Output2

    However, if you still want to use LinearLayout you can limit the size of name TextView using maxWidth property. But in this case if price text is small, your name text will still go to next line as you defined maximum width. But this won't happen in case of RelativeLayout.