2013-02-26 63 views
0

我在一個線性佈局下在一行(水平)中有8個(八個)按鈕。問題是這些按鈕看起來像矩形,而我希望它們看起來像方形。Android:UI線性佈局和按鈕

<Button 
     android:id="@+id/button25" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_gravity="right" 
     android:layout_weight="0.125" 
     android:background="#ffffffff" /> 

有人能指導我做什麼需要做的,以便這些矩形變成正方形。

回答

1

如果對寬度和高度都使用固定尺寸,則會得到一個正方形,但是您失去了自動調整大小的LinearLayout的功能。在你的情況下,你不知道每個按鈕的寬度,直到佈局完成。 View中的post()方法是你的朋友。

final Button button1 = (Button) findViewById(R.id.button25); 
first.post(new Runnable() { 
    public void run() { 
     LinearLayout.LayoutParams params = 
      (LinearLayout.LayoutParams) button1.getLayoutParams(); 
     params.height = button1.getWidth(); 
    } 
}); 

爲了確保按鈕大小正確的佈局應該是這個樣子:

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="horizontal" 
    android:weightSum="5"> <!-- or however many buttons there are --> 
    <Button 
     android:id="@+id/button1" 
     android:layout_width="0dp" 
     android:layout_weight="1" 
     android:layout_height="wrap_content" /> 
    <!-- other buttons go here --> 
</LinearLayout> 

這隻需要照顧的第一個按鈕的,但你可以弄清楚如何做休息。

1

而不是設置

android:layout_width="match_parent" 
    android:layout_height="match_parent" 

指定爲寬度和高度的值,

android:layout_width="160dip" 
    android:layout_height="160dip" 

的同時刪除

android:layout_weight="0.125" 

因此,代碼是像

 <Button 
    android:id="@+id/button25" 
    android:layout_width="160dip" 
    android:layout_height="160dip" 
    android:layout_gravity="right" 

    android:background="#ffffffff" /> 

It Works!