2011-08-26 60 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

對我無效。 –

相關問題