Search code examples
androidandroid-layoutlayoutandroid-4.0-ice-cream-sandwich

How to make Android view width = (parent width - some constant)


I have a layout and I'm trying to have a view fill all the remaining space, EXCEPT some 50dp width image at the end. When I set the first view's width to match_parent, it occupies the whole view, and whatever I set to the image's width, it's placed outside the screen bounds. Here is what's happening:

enter image description here

But I want it like this: (achieved by setting the first view's width to a constant just to demo, which I definitely don't want as it should fill a dynamic amount of width)

enter image description here

Here is my current layout:

enter image description here

The problem is at the LinearLayout (vertical) which is just below the avatar view in the hierarchy. It occupies the correct space, but it's children are not acting the way I want.

How can I achieve the desired layout?


Solution

  • Take a look on this example. Main idea is to set android:layout_width="0dp" and android:layout_weight="1" for the view which has to take all available space. In mine case it is TextView in you case it can be another layout or anything else.

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:orientation="horizontal"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            ....
            />
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            ....
            />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            ...
            />
    
    </LinearLayout>
    

    Update

    More information can be found here question.