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...
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...
And I'm trying to do this in the XML layout (not programmatically).
Below that, the layout_height=0 and layout_weight=1 attributes on the RelativeLayout cause it to take up all the remaining space. You can then center the button in the RelativeLayout . You can play with padding on the button to get it to the size you want.
To center a view, just drag the handles to all four sides of the parent.
To center something in a RelativeLayout, you use android:layout_centerInParent="true" on the child. If you try to center several childs, they'll end up under/over each other.
If you want to make it center then use android:layout_centerVertical="true" in the TextView. my Relative Layout has fill_parent for both height and width.
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>
There's unfortunately no easy way to do this. You can either nest layouts, or do it at runtime. The simplest way is to nest layouts:
<LinearLayout
android:width="match_parent"
android:height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/my_top_image"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/my_button_label"/>
</RelativeLayout>
</LinearLayout>
This puts the image at the top. Below that, the layout_height=0
and layout_weight=1
attributes on the RelativeLayout
cause it to take up all the remaining space. You can then center the button in the RelativeLayout
. You can play with padding on the button to get it to the size you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With