2013-08-26 33 views
11

這是一張可以讓你瞭解我想要什麼:如何在相對佈局中將元素與另一個元素的中心對齊?

enter image description here

我有這個綠色的元素已經在我親戚的佈局設置,並且我要的是把另一個元素(黑的在圖片)在它上面,所以它完全居中在綠色元素的中間。

請記住,黑色元素沒有固定的寬度,並且寬度比綠色寬。

有東西像android:layout_alignLeft和android:layout_alignRight這將有助於如果我想它左對齊或右對齊,但據我所知沒有android:layout_alignCenter,所以我不知道如何做到這一點事情...

+0

[從另一視圖的Android相對佈局alignCenter](可能重複http://stackoverflow.com/questions/5487864/android-relative-layout-aligncenter-from -another-view) – tir38

回答

17

正如你所說,把兩個元素放在RelativeLayout

於是,「CENTER_HORIZONTAL」這兩個元素的屬性設置爲true,然後將綠色元素的「下面」屬性設置爲黑色元素的ID。

下面是完整的例子:

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

    <View 
     android:id="@+id/view1" 
     android:layout_width="100dp" 
     android:layout_height="40dp" 
     android:background="@color/Black" 
     android:layout_centerHorizontal="true" 
     android:layout_centerVertical="true" /> 

    <View 
     android:id="@+id/view2" 
     android:layout_height="100dp" 
     android:layout_below="@+id/view1" 
     android:background="@color/Green" 
     android:layout_centerHorizontal="true" /> 

</RelativeLayout> 

( 「center_vertical」 是有點兒可選)

或者在這裏,不管對方意見位置:

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

    <View 
     android:id="@+id/view1" 
     android:layout_width="100dp" 
     android:layout_height="40dp" 
     android:background="@color/Black" 
     android:layout_centerVertical="true" /> 

    <View 
     android:id="@+id/view2" 
     android:layout_width="40dp" 
     android:layout_height="100dp" 
     android:layout_below="@+id/view1" 
     android:layout_alignLeft="@+id/view1" 
     android:layout_alignRight="@+id/view1" 
     android:layout_marginLeft="30dp" 
     android:layout_marginRight="30dp" 
     android:background="@color/Green" /> 

</RelativeLayout> 

(在這種情況下,邊距將定義第二個Views寬度)

這是最終的結果:

enter image description here

+1

事情是,center_horizo​​ntal將相對於父母的元素居中。我不希望它們位於父項的中心,我只想將黑色元素對齊到綠色元素的中心,而不管它們在父項中的位置。 –

+2

我更新了我的答案:) –

+0

對齊smthng的左側和右側真的很棒,謝謝 – OFFmind

相關問題