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 loo开发者_开发知识库k 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
Try setting the layout_width to wrap_content vs. 0dp.
Width/Height seem to always ahve to be set together,.. This is working in my view
<Button
android:text="Center"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:id="@+id/selectionCenterButton"
android:minWidth="50dp"
android:minHeight="50dp"
android:maxWidth="100dp"
android:maxHeight="50dp"
android:layout_weight="1" />
The button's parent is set to wrap content, so scales down, but up to a max of 400 wide (4 buttons)
精彩评论