How to center a view using RelativeLayout?

Gus picture Gus · Aug 28, 2012 · Viewed 18.3k times · Source

I wanted to know how to center a View between two other views (or between a view and the parent edge) using RelativeLayout.

For example, if I have the following...

enter image description here

How do I vertically center the Button between the ImageView and the bottom of the screen using RelativeLayout?

I'm looking for a solution where...

  • the Button is not stretched in any way
  • there are no nested layouts

And I'm trying to do this in the XML layout (not programmatically).

Answer

Shrikant picture Shrikant · Aug 28, 2012

You can use following:

<RelativeLayout 
        android:layout_below="@id/theImageView"
        android:align_parentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="200dp" >    


        <Button 
            android:id="@+id/btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"            
            android:onClick="onClickButton"
            android:textSize="20sp"
            android:text="Go"/>

    </RelativeLayout>