2012-06-05 51 views
11

我試圖在作爲基礎的RelativeLayout中水平居中幾個視圖。RelativeLayout重心無法正常工作

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:gravity="center_horizontal" 
    android:background="@android:color/transparent" > 

這是行不通的。我爲其中一個觀點設置了centerInParenttrue並且確實有效。然而,我不能使用這個解決方案,因爲我有兩個並排的視圖需要集中在一起。試圖優化這個,所以我想避免嵌套佈局,尤其是線性,在彼此的內部。

有什麼明顯的我失蹤了嗎?我認爲這是屬於這種情況的。

回答

1

因此,我對這個問題的修復只是爲了利用textview的複合可繪製功能。我只是拋棄了按鈕並使用drawableRight來顯示搜索圖標。

4

您需要將多個佈局嵌套在一起。要在RelativeLayout中居中放置某個東西,可以在子節點上使用android:layout_centerInParent="true"。如果你試圖把幾個孩子放在中間,他們最終會在對方下面/下方。

因此,例如,您可以使用具有兩個視圖的LinearLayout作爲RelativeLayout的子項,LinearLayout具有android:orientation="horizontal"android:layout_centerInParent="true"。 LinearLayout現在應該在RelativeLayout中居中,兩個孩子相鄰。

+1

我真的在努力優化這個屏幕,因爲它是主要活動。因此,我真的很想避免嵌套LinearLayouts。我實際上從這個應用程序中刪除了所有的線性佈局,因爲它們效率很差。 –

+3

那麼,如果你不能嵌套佈局,那麼沒有辦法做到這一點(好看)。至少據我所知。 –

2

在LinearLayout中包裝兩個視圖,然後將LinearLayout放置在RelativeLayout中,就像您爲單個TextView所做的那樣。

+0

不想嵌套。這仍然不能解釋centerInParent在設置爲true時工作的問題,但在重力設置爲center_horizo​​ntal時不起作用 –

+0

在文本視圖中嘗試使用android:layout_gravity =「center horizo​​ntal」。 – Barak

+0

不,謝謝你的回覆,但這不會起作用。我需要兩個按鈕並排放置,因此center_horizo​​ntal會將每個按鈕放在一起。 –

8

我回答了一個類似的問題,涉及三個視圖,而不使用嵌套的ViewGroups。

https://stackoverflow.com/a/13279846/1011746

這API 11.

測試對於兩個水平視情況:

<RelativeLayout 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:gravity="center" 
    android:background="@android:color/black" 
    > 
    <Button 
    android:id="@+id/apply" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerInParent="true" 
    android:text="APPLY" 
    android:textSize="20sp" 
    /> 
    <Button 
    android:id="@+id/undo" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerInParent="true" 
    android:text="UNDO" 
    android:textSize="20sp" 
    android:layout_toRightOf="@id/apply" 
    /> 
</RelativeLayout> 

對於兩個視圖垂直情況下:

<RelativeLayout 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:gravity="center" 
    android:background="@android:color/black" 
    > 
    <Button 
    android:id="@+id/apply" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerInParent="true" 
    android:text="APPLY" 
    android:textSize="20sp" 
    /> 
    <Button 
    android:id="@+id/undo" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerInParent="true" 
    android:text="UNDO" 
    android:textSize="20sp" 
    android:layout_below="@id/apply" 
    /> 
</RelativeLayout> 
+0

該解決方案僅適用於視圖可以堆疊在一行中時,如果佈局更復雜,唯一的解決方案是使用嵌套佈局作爲其他答案建議或採取不同的評價。 – TheIT