2013-01-02 52 views
0

我在我的Android應用程序中有一個相當簡單的活動,顯示三個按鈕,每個按鈕都啓動一個不同的活動。目前,我使用RelativeLayout將中間按鈕水平和垂直居中,然後將頂部和底部按鈕從中間按鈕放置30dp(也水平居中)。Android:居中放大按鈕百分比

然而,我想要做的是使按鈕拉伸爲屏幕寬度的一定百分比。我無法弄清楚如何做到這一點,並保持按鈕居中。在按鈕兩側的LinearLayout中是否有一個可用作「填充符」的好對象(所以我可以設置權重)?或者有沒有辦法做到這一點,不涉及LinearLayout?

的XML的,因爲它代表的佈局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <Button 
     android:id="@+id/button1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_above="@+id/button2" 
     android:layout_centerHorizontal="true" 
     android:layout_marginBottom="30dp" 
     android:onClick="button1Callback" 
     android:text="@string/button1Label" /> 

    <Button 
     android:id="@+id/button2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_centerHorizontal="true" 
     android:layout_centerVertical="true" 
     android:onClick="button2Callback" 
     android:text="@string/button2Label" /> 

    <Button 
     android:id="@+id/button3" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/button2" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="30dp" 
     android:text="@string/button3Label" /> 

</RelativeLayout> 
+0

你能以某種方式證明你想要它看起來像什麼嗎?油漆,吝嗇等我想我明白了,但我可能是錯的。 – Ahmad

+0

如何根據屏幕百分比首先修改寬度?看着這個,如果你把寬度改成100dp,它們都應該保持居中。 – leenephi

回答

1

肯定。視圖或框架都可以工作。

<LinearLayout ... android:orentation="horizontal"> 
    <View android:layout_height="0dp" 
    android:layout_width="0dp" 
    android:layout_weight="60" /> 
    <Button android:layout_height="wrap_content" 
    android:layout_width="0dp" 
    android:layout_weight="20" /> 
    <View android:layout_height="0dp" 
    android:layout_width="0dp" 
    android:layout_weight="20" /> 
</LinearLayout> 

作爲一個墊片工作得很好,據我所知,似乎是完全無害的。我在我的應用中使用了相當多的東西(儘管說實話,我的大部分按鈕都是固定寬度的)。

在某一點上,我實際上是用比例佈局編寫了一個自定義視圖。但最終我最終沒有使用它。在幾乎所有情況下,您都可以獲得與線性佈局中明智應用的權重等效的比例佈局。