2013-08-26 11 views
11

は絵です:どのように要素を相対的なレイアウトで他の要素の中央と上に配置することができますか?あなたは私が欲しいものを理解できるように、ここで

enter image description here

私はすでに私の相対的なレイアウトでセットアップし、この緑の要素を持っている、と私がしたいことで別の要素(黒1を置くことですpic)上に置かれるので、緑の要素の真ん中に正確にセンタリングされます。

黒の要素は一定の幅を持たず、緑の要素よりも幅が広いことに注意してください。

アンドロイドのようなものがあります:layout_alignLeftとandroid:layout_alignRightこれは左または右に揃えたい場合に役立ちますが、アンドロイド:layout_alignCenterがないので、これを行う方法はわかりません物...

+0

可能重複(http://stackoverflow.com/questions/5487864/android-relative-layout-aligncenter-from -another-view) – tir38

答えて

17

あなた自身が言ったように、RelativeLayoutの中に両方の要素を入れてください。

そして、真の両方の要素の「center_horizo​​ntal」プロパティを設定し、黒の要素の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> 

(中この場合、マージンは2番目のビュー幅を定義します)

これは最終的な結果である:[他のビューからのAndroid相対レイアウトalignCenter]の

enter image description here

+1

事実、center_horizo​​ntalは要素を親の中心に合わせて配置します。そして、私はそれらが親の中心にあることを望んでいません、私はちょうど親の中で彼らの位置に関係なく、緑の要素の中心になるように黒の要素を揃えたいです。 –

+2

私の答えを更新しました: –

+0

smthngの右と左に一瞬に揃えて本当に素晴らしいです、ありがとう – OFFmind

関連する問題