2013-01-06 76 views
0

我想使2按鈕佔據屏幕寬度的一半,但是我真的只有一個按鈕來到屏幕上,並採取全屏幕寬度。我想要所有的分辨率,所以不想修改寬度。一個按鈕將左半等將右半這可怎麼辦android簡單佈局

<?xml version="1.0" encoding="utf-8"?> 
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:gravity="center"> 


     <Button 
      android:id="@+id/button1" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:text="Button" 
      android:layout_gravity="left" /> 


     <Button 
      android:id="@+id/button2" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:text="Button" 
      android:layout_gravity="right" /> 

    </LinearLayout> 

</ScrollView> 
+0

此問題已在stackoverflow上被詢問了幾次 - 一個示例:http://stackoverflow.com/questions/11286147/android-setting-button-width-half-the-screen/11286169#11286169 - 如果您使用你會發現更多的搜索 –

回答

2

使用以下佈局技術。使用Linear Layout。將layout_width分配給0dip。將layout_weight分配給每個按鈕1,以便它們佔用等於總寬度。如果你希望他們佔據一半屏幕的高度,而不是寬的,在上面XML layout_widthlayout_height之間改變佈局的orientationvertical和交換價值:爲每一個按鈕的layout_heightmatch_parent

<LinearLayout 
     android:id="@+id/LinearLayout1" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="horizontal"> 

     <Button 
      android:id="@+id/ButtonLeft" 
      android:layout_width="0dip" 
      android:layout_height="match_parent" 
      android:layout_weight="1" 
      android:text="ButtonLeft" 
      /> 
     <Button 
      android:id="@+id/ButtonRight" 
      android:layout_width="0dip" 
      android:layout_height="match_parent" 
      android:layout_weight="1" 
      android:text="ButtonRight" 
      /> 

    </LinearLayout> 

PS。

關於layout_weight

layout_weight決定父元素空間是如何劃分之間它的孩子。如果你想在你的按鈕之間按1:4的寬度進行分割,那麼你可以將layout_weight的1個按鈕分配給「1」,另一個按鈕分配給「3」 - > 1 /(1 + 3)= 1/4 。 layout_weight又是如何工作的 - 高度還是寬度? layout_weight從免費或未使用的空間分發。在上述佈局中,我們將0dip分配給按鈕的寬度。因此,根據layout_weight,父項的水平空間或寬度未使用或空閒,並在您的按鈕之間分配。希望這可以幫助。

+0

完美它解決了這個問題,但我不明白的佈局重量屬性,你可以給我有用的指導呢? –

+0

我已更新我的答案,以包含'layout_weight'的概念 –

3

可以定義layout_weight定義視圖的大小。使用layout_width0dp是使用重量設置(根據lint)的最佳方式。當兩個按鈕具有相同的值時,兩者都使用50%的寬度。玩弄這些價值觀以獲得這種感覺。

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <Button 
     android:id="@+id/button1" 
     android:layout_width="0dp" 
     android:layout_height="wrap_content" 
     android:text="Button" 
     android:layout_weight="1"/> 

    <Button 
     android:id="@+id/button2" 
     android:layout_width="0dp" 
     android:layout_height="wrap_content" 
     android:text="Button" 
     android:layout_weight="1" /> 

</LinearLayout> 
+0

完美它解決了這個問題,但我不明白的佈局權重屬性,你能給我有用的指導呢? –

+1

有很多[問題](http://stackoverflow.com/questions/3995825/what-does-androidlayout-weight-mean)和答案。只需使用搜索。 – WarrenFaith