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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With