2011-03-23 96 views
20

組佈局中的邊距似乎不起作用。LinearLayout,RelativeLayout等邊距不能按預期方式工作

例如,

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

    <Button 
     android:id="@+id/button" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:text="I'm a button" /> 

</LinearLayout> 

應顯示與在所有側面40P邊距的按鈕。但是,它的右側和底部有80p的餘量。

我做錯了什麼? 這是一個錯誤?

解決方法是使用重力,但這僅適用於平差。

順便說一句,有一個類似的問題posted here,但沒有得到回答。

+0

嘗試設置按鈕,中心將它包裝水平 – Nepster 2014-07-17 07:55:38

回答

20

android:padding="40dp"上的LinearLayout或android:layout_margin="40dp"上的按鈕會給你你想要的效果。填充定義了視圖邊緣與其內容之間的空間,佈局邊距在視圖的側面定義了額外的空間。

+1

保證金應該利潤率'40dp'了'從四面八方LinearLayout'。奇怪的是,它沒有按預期工作。 – 2015-04-22 08:05:40

11

問題實際上是FrameLayout解釋邊距的方式。 setContentView()將您的「主要」佈局附加到FrameLayout,這是視圖層次結構的實際根目錄(您可以使用層次結構查看器查看),並通過電話向您提供。

頁邊距由父頁面佈局管理,因此在這種情況下主頁面FrameLayout。我不知道它是一個功能還是一個bug,但這就是這個佈局解釋利潤的方式。

那麼,我輸入時已經發布瞭解決方案:使用填充代替。

+0

我記得使用FrameLayout在蜂窩時間幀期間處理邊距的方式修復了一些錯誤,並且它涉及默認的重力設置。這可能確實是一個錯誤。 :) – adamp 2011-03-24 01:02:21

+0

另一種方法是設置android:layout_gravity =「top | left」來查看FrameLayout中的內容。 – VinceStyling 2013-11-14 11:10:22

5

,如果你需要一個佈局中設置保證金,只需用另一個線性或相對佈局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 

    <LinearLayout android:layout_margin="40dip" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <Button android:id="@+id/button" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:text="I'm a button" /> 

    </LinearLayout> 

</LinearLayout> 
+2

這是更好的答案。填充不一定就是你想要的,特別是如果你的佈局有可見的背景。 – 2014-03-11 04:23:06

+0

你應該避免嵌套佈局,只是爲了給內部邊界留出空間。 http://developer.android.com/training/improving-layouts/optimizing-layout.html。這不是更好的答案。 – 2015-02-25 10:03:42