2012-06-01 20 views
2
<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/frameLayout1" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="@drawable/background_gradient" > 

    <RelativeLayout 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:gravity="center" > 

     <ImageButton 
      android:id="@+id/buttonLog" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:background="@drawable/log" 
      android:onClick="log" /> 

    </RelativeLayout> 

</FrameLayout> 

我期待我的按鈕出現在中心屏幕的FILL_PARENT行爲不。但是,它出現在屏幕的頂部中心(即按鈕居中水平,但不垂直)。Android的 - 如預期中的RelativeLayout

在我看來,RelativeLayout的行爲就像是用「wrap_content」而不是「fill_parent」定義的。

有趣的是,如果我舉一個實際值,以我的RelativeLayout height屬性(安卓layout_height),如:

<RelativeLayout 
     android:layout_width="fill_parent" 
     android:layout_height="100dp" 
     android:gravity="center" > 

然後按鈕選擇正確的行爲(即按鈕也垂直居中) 。但我不想使用實際值。我想使用fill_parent!爲什麼它不適用於「fill_parent」?

有人知道發生了什麼嗎?

預先感謝您!

回答

1

你爲你RelativeLayoutlayout_widthlayout_height同時指定fill_parent,因此它填補了它的父視圖。 默認情況下,無論您使用大小的fill_parent,相對佈局都會將其子項排列在左上角。

你應該通過採取RelativeLayout's自己的屬性集,它可以幫助你安排孩子的意見相對對方或者其母公司的優勢,達到理想的方面:

<ImageButton 
    android:id="@+id/buttonLog" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerInParent="true" 
    android:background="@drawable/log" 
    android:onClick="log" /> 

使用android:layout_centerInParent即可做到這一點。此屬性如果設置爲true,則將此子級在其父級中水平和垂直居中。

+0

嗨rekaszeru。感謝回覆。據我所知,相對佈局會默認安排從左上角開始的孩子。然而,這就是爲什麼我在該RelativeLayout中設置了android:gravity =「center」屬性,所以它的子節點居中(但這不會發生)。你能解釋爲什麼中心屬性在這裏沒有做任何事嗎? – Tiago

+1

請參閱此解釋:http://stackoverflow.com/a/6819801/506879另請參閱'RelativeLayout's'屬性:http://developer.android。com/reference/android/widget/RelativeLayout.LayoutParams.html沒有'gravity'屬性。 – rekaszeru

+1

哇!沒有引力屬性...我實際上使用了Eclipse的代碼完成功能,當我點擊(Ctrl +空格鍵)時,它確實向我展示了相對佈局的引力屬性。一旦這個完成是由Google完成的(最近它被納入到了Android插件中),我期望的最少的是它是正確的......我想我不能依賴於Eclipse的建議。我會一直檢查網站上的文檔。我不得不說,這是非常惱人的,雖然...感謝您的幫助rekaszeru! – Tiago

4

RelativeLayout要求您指定佈局中元素的位置。我沒有看到任何layout_below或layout_toLeftOf標記。重力適用於LinearLayouts。一般來說,LinearLayouts更易於使用,而且它們可以更好地適應不同的屏幕尺寸。我建議你用LinearLayout替換RelativeLayout,並用LinearLayout替換FrameLayout。通常,如果您想使用多個重疊佈局,則不使用FrameLayout。

我建議你使用Android SDK參考文檔中的佈局,喜歡這裏讀了起來:http://bit.ly/djmnn7

+0

Humm,之前我沒有使用RelativeLayouts屬性。但無論如何,我從現在開始就會考慮你的建議。謝謝! (+1)。 – Tiago

+0

您可以使用RelativeLayouts執行的所有操作都可以在LinearLayouts中完成,除非在精心製作佈局時它會變得複雜。 LL的優勢在於,它在所有設備上始終保持良好的狀態。使用具有適當權重的嵌套LL來獲得所需的UI佈局。查看佈局寬度,高度和重量的參考文檔。 – Christine