Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does maxWidth on a Button not work and how to work around it?

I have two buttons on the layout, and on a large-screen device (tablets) I want to cap their width so they don't look ridiculous. I expected to use the maxWidth attribute but it apparently does nothing in my scenario. Here's the layout definition - the buttons use up the full width of the layout, ignoring any value in maxWidth.

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
>
<Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:maxWidth="100dp"
    android:text="Button 1"
/>
<Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:maxWidth="100dp"
    android:text="Button 2"
/>
</LinearLayout>

Why, and how to workaround this (apparently crazy) limitation?

like image 673
Ollie C Avatar asked Aug 26 '11 13:08

Ollie C


2 Answers

Remove the android:layout_weight="1" line from both buttons.
Add android:minWidth="50dp" and android:layout_width="wrap_content"

EDIT:

You need to calculate the button sizes manually depending on the screen size. First you need to have a standard screen size set. For example, If the you develop the app on a screen width 400px, and the button is 100px wide, then the formula for maintaining the same button width to screen width ratio on all devices will be as follows

 DisplayMetrics metrics = new DisplayMetrics();
 getWindowManager().getDefaultDisplay().getMetrics(metrics);
 buttonWidth = 100 * (metrics.widthPixels/400); 

Use case:
If screen width = 480px, then button width should be 120px.

like image 175
Ronnie Avatar answered Nov 08 '22 08:11

Ronnie


The good way of solving this is to create multiple layout for different combination of screen resolution. When you get at some max stretch, create a new layout that have fixed value where needed. See the section about "Use layout alias" in http://developer.android.com/training/multiscreen/screensizes.html#TaskUseAliasFilters

like image 30
darkzangel Avatar answered Nov 08 '22 07:11

darkzangel