【问题标题】:Why does maxWidth on a Button not work and how to work around it?为什么按钮上的 maxWidth 不起作用以及如何解决它?
【发布时间】:2011-08-26 13:22:59
【问题描述】:

我在布局上有两个按钮,在大屏幕设备(平板电脑)上,我想限制它们的宽度,以免它们看起来很荒谬。我希望使用 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>

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

【问题讨论】:

  • 为什么按钮 layout_width 是 0dp 而不是 wrap_content?
  • @antlersoft - 0dp 宽度与与兄弟元素匹配的 layout_weight 相结合将确保它们彼此的宽度相同

标签: android android-layout android-button


【解决方案1】:

从两个按钮中删除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); 

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

【讨论】:

  • 为什么?然后按钮根本不会缩放,宽度为零
  • 这就是导致按钮拉伸以填充整个布局宽度的原因。同时设置 minwidth 并将宽度更改为 wrap_content 而不是 0dp。
  • 如果我删除 layout_weight 按钮将不会缩放,这是我想要它做的。我想要一个可以随设备尺寸缩放的按钮,但只能缩放到最大尺寸。
  • 如果您使用dp 作为尺寸,那么drawables 将自动缩放以适应不同的密度。你不能为不同的尺寸做它。
  • 我可以动态地做到这一点,但这是一种相当暴力的方法。我希望能够说服框架按我的预期工作。我将研究 Button 的子类化以包括动态调整大小,但也会考虑使用各种布局变体来避免这种需要。
【解决方案2】:

解决这个问题的好方法是为不同的屏幕分辨率组合创建多个布局。当你达到最大拉伸时,在需要的地方创建一个具有固定值的新布局。请参阅http://developer.android.com/training/multiscreen/screensizes.html#TaskUseAliasFilters中有关“使用布局别名”的部分

【讨论】:

    【解决方案3】:

    尝试将 layout_width 设置为 wrap_content 与 0dp。

    【讨论】:

    • 这是我尝试过的众多变体之一。没有什么不同。
    【解决方案4】:

    宽度/高度似乎总是要设置在一起,..这在我看来是可行的

            <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" />
    

    按钮的父级设置为包裹内容,因此会缩小,但最大宽度为 400(4 个按钮)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-03
      • 1970-01-01
      • 2012-05-20
      • 2020-10-03
      • 2011-10-08
      • 2011-08-14
      • 2015-07-15
      • 1970-01-01
      相关资源
      最近更新 更多