How can I align an element to be in center of and above another element in relative layout?

David Simka picture David Simka · Aug 26, 2013 · Viewed 19.4k times · Source

Here's a picture so you can understand what I want:

enter image description here

I have this green element already set up in my relative layout, and what I want is to put another element (the black one in the pic) above it so it gets centered exactly in the middle of the green element.

Keep in mind that the black element doesn't have a constant width, and it's bigger in width than the green one.

There are stuff like android:layout_alignLeft and android:layout_alignRight which would be helpful if I wanted it aligned left or right, but as far as I know there is no android:layout_alignCenter so I don't know how to do this thing...

Answer

Philipp Jahoda picture Philipp Jahoda · Aug 26, 2013

As you said yourself, put both elements inside a RelativeLayout.

Then, set the "center_horizontal" property of both elements to true, and then set the "below" property of the green element to the id of the black element.

Here is the complete example:

<?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" is kinda optional)

Or here, regardless of the other Views position:

<?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>

(In this case, the margins will define the second Views width)

This is the end result:

enter image description here