2015-06-19 38 views
-1

我有這樣的佈局:如何在LinearLayout中水平對齊3個固定寬度按鈕?

<LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" 
     android:paddingTop="32dp"> 

     <Button 
      android:layout_width="100dp" 
      android:layout_height="wrap_content" 
      android:text="Button1"/> 

     <Button 
      android:layout_width="100dp" 
      android:layout_height="wrap_content" 
      android:text="Button2"/> 

     <Button 
      android:layout_width="100dp" 
      android:layout_height="wrap_content" 
      android:text="Button3"/> 

    </LinearLayout> 

欲水平對齊這些3 修復寬度按鈕。請問你能幫幫我嗎 ?

+0

您有什麼問題試試這個,變化的重量? – Amsheer

+0

你可以給每個按鈕分配android:layout_weight =「1」 – Moinkhan

回答

1

基本上有涉及3個步驟。

  1. 將weightSum =「3」設置爲父佈局。這意味着整個layout_weights的總和爲3.

  2. 將layout_weight =「1」設置爲每個單獨按鈕。所以每個按鈕的大小都是父級的1/3。

  3. 最後設置layout_width =「0dp」,這很重要,因爲在這裏你不必設置視圖的寬度。它將由佈局處理程序自動設置。

    <Button 
         android:layout_width="0dp" 
         android:layout_height="wrap_content" 
         android:text="Button1" 
         android:layout_weight="1"/> 
    
        <Button 
         android:layout_width="0dp" 
         android:layout_height="wrap_content" 
         android:text="Button2" 
         android:layout_weight="1"/> 
    
        <Button 
         android:layout_width="0dp" 
         android:layout_height="wrap_content" 
         android:text="Button3" 
         android:layout_weight="1"/> 
    
    </LinearLayout> 
    
+0

謝謝,但我想保持我原來的寬度(100dp)。這就是爲什麼我發佈這個問題。 – anthony

+0

如果你想設置100dp。那你爲什麼要改變你寫的代碼? –

2

嘗試此代碼

<RelativeLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:paddingTop="32dp"> 

    <Button 
     android:layout_width="100dp" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:text="Button1"/> 

    <Button 
     android:layout_width="100dp" 
     android:layout_height="wrap_content" 
     android:layout_centerHorizontal="true" 
     android:text="Button2"/> 

    <Button 
     android:layout_width="100dp" 
     android:layout_height="wrap_content" 
     android:layout_alignParentRight="true" 
     android:text="Button3"/> 

</RelativeLayout> 
0

根據您的要求

<LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:weightSum="9" 
     android:orientation="horizontal" 
     android:paddingTop="32dp"> 
     <Button 
      android:layout_width="0dp" 
      android:layout_weight="3" 
      android:layout_height="wrap_content" 
      android:text="Button1"/> 
     <Button 
      android:layout_width="0dp" 
      android:layout_weight="3" 
      android:layout_height="wrap_content" 
      android:text="Button2"/> 
     <Button 
      android:layout_width="0dp" 
      android:layout_weight="3" 
      android:layout_height="wrap_content" 
      android:text="Button3"/> 
    </LinearLayout>