为什么Button上的maxWidth不起作用以及如何解决它?

Oll*_*e C 12 android android-layout android-button

我在布局上有两个按钮,在大屏幕设备(平板电脑)上,我想限制它们的宽度,这样它们看起来并不荒谬.我希望使用maxWidth属性,但它在我的场景中显然没有任何作用.这是布局定义 - 按钮使用布局的整个宽度,忽略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>
Run Code Online (Sandbox Code Playgroud)

为什么,以及如何解决这个(显然是疯狂的)限制?

Ron*_*nie 11

android:layout_weight="1"从两个按钮中删除该行.
添加android:minWidth="50dp"android:layout_width="wrap_content"

编辑:

您需要根据屏幕大小手动计算按钮大小.首先,您需要设置标准屏幕尺寸.例如,如果您在宽度为400px的屏幕上开发应用程序,并且按钮宽度为100px,那么button width to screen width在所有设备上保持相同比例的公式将如下所示

 DisplayMetrics metrics = new DisplayMetrics();
 getWindowManager().getDefaultDisplay().getMetrics(metrics);
 buttonWidth = 100 * (metrics.widthPixels/400); 
Run Code Online (Sandbox Code Playgroud)

使用案例:
如果屏幕宽度= 480px,则按钮宽度应为120px.

  • 为什么?然后按钮根本不会缩放,宽度为零 (2认同)