views:

109

answers:

2

How can I set max width of horizontal LinearLayout? So if the contents is short (say, some text), the layout shrinks and if the contents is longer - it will not expand more than some max width value.

I prefer doing it at the XML level.

Pls let me know if my question is not clear enough.

Thanks in advance

+2  A: 

You could just use left and right padding for this, it's what it's there for really. Set a left and right padding of 100 and there will always be a minimum of 100 blank space at either side.

Example code...

<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="100dip" 
android:paddingRight="100dip" 
android:gravity="center">
...
</LinearLayout>

In this case I'm using density independent pixels to keep it looking the same across devices.

Zulaxia
can you pls post a source code?
Asahi
perhaps I need to clarify: I need layout to change its size. Setting padding will just restrain the contents.
Asahi
It would change size since it is set to wrap_content. The padding just prevents it filling the screen width, which is what you asked for. I think you need to clarify how this doesn't fit your needs.
Zulaxia
Thanks Zulaxia for the direction - what I needed is to add another layout as wrapper between the contents and the top layout.
Asahi
A: 

This does it:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" 
android:layout_width="fill_parent"
android:layout_height="wrap_content" 
android:paddingLeft="100dip"
android:paddingRight="100dip">
<LinearLayout android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:id="@+id/TheLayout"
    android:layout_gravity="right">
    <TextView android:id="@+id/TextView01" 
        android:layout_height="wrap_content"
        android:layout_width="fill_parent" 
        android:layout_weight="1"
        android:text="this is my text." 
        android:layout_gravity="center_vertical">
    </TextView>
    <ImageView android:id="@+id/ImageView01"
        android:layout_height="wrap_content" 
        android:background="@drawable/icon"
        android:layout_width="fill_parent">
    </ImageView>
</LinearLayout>
</LinearLayout>
Asahi