Android LinearLayout horizontally or vertically oriented items fill remaining space

Total Post:45

Points:315
 1356  View(s)
Ratings:
Rate this:

I wonder if it is possible to have two items in a LinearLayout one wraps its content and the other fills the remaining horizontal space. I do this frequently in WPF (.NET) by specifying HorizontalAlignment="Stretch".

For example:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="24dp"
    android:background="#0000FF"/>
<ImageView
    android:layout_width="match_parent"
    android:layout_height="24dp"
    android:background="#FF0000"/>

When I do this the second ImageView fill the whole horizontal space as I expected. I tried to set both wrap_content and use gravity such as android:gravity="start" and android:gravity="fill_horizontal" for the second one it did not worked.

NOTE: I can achieve something similar by specifying weight attribute. But this is providing a division according to the percent value. This is not I want.

  1. Post:30

    Points:210
    Re: Android LinearLayout horizontally or vertically oriented items fill remaining space

    You can do this using the weight attribute itself. Try the following method

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="24dp"
        android:background="#0000FF"/>
    <ImageView
        android:layout_width="0dp"
        android:layout_height="24dp"
        android:layout_weight="1"
        android:background="#FF0000"/>

    include this in your horizontal linear layout

      Modified On Apr-06-2018 06:58:47 AM

Answer