2011-08-26 284 views
12

我在布局上有两个按钮,而在大屏幕设备(平板电脑)上我想限制它们的宽度,所以它们看起来不可笑。我期望使用maxWidth属性,但它在我的场景中显然没有任何作用。这里是布局定义 - 按钮使用布局的整个宽度,忽略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> 

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

+0

中有关“使用布局别名”的部分为什么按钮layout_width 0dp而不是wrap_content? – antlersoft

+0

@antlersoft - 0dp宽度结合layout_weight与兄弟元素相匹配,可确保它们的宽度相同 – ataulm

回答

11

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

编辑:

您需要手动计算按钮大小取决于屏幕尺寸。首先你需要有一个标准的屏幕尺寸设置。例如,如果你开发上的屏幕宽度400像素的应用程序,并且该按钮是100像素宽,则用于保持上的所有设备的相同button width to screen width比将如下

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

使用案例式:
如果屏幕宽度= 480px,那么按钮宽度应该是120px。

+2

为什么?然后这些按钮根本不会缩放,并且宽度为零 –

+0

这就是导致按钮拉伸以填充整个布局宽度的原因。也设置最小宽度,并将宽度更改为'wrap_content'而不是0dp。 – Ronnie

+0

如果我删除layout_weight,按钮将不会缩放,这是我想要的。我想要一个按比例缩放设备尺寸但只能达到最大尺寸的按钮。 –

0

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

+0

这是我试过的很多变体之一。它没有任何不同。 –

0

宽度/高度似乎总是ahve被设置在一起,。这是在我看来,工作

 <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按钮)

+0

对我无效。 –

相关问题