Ccna final exam - java, php, javascript, ios, cshap all in one. This is a collaboratively edited question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
Tuesday, April 17, 2012
Can you center a Button in RelativeLayout?
I'm trying to center a button in relative layout, is this possible? I've tried the Gravity and Orientation functions but they don't do anything.
Setting the gravity of the RelativeLayout itself will affect all of the objects placed inside of it. In this case, it's just the button. You can use any of the gravity settings here, of course (e.g. center_horizontal, top, right, and so on).
Try
ReplyDeleteandroid:layout_centerHorizontal="true"
Exactly like this, it works for me:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff0000"
>
<Button
android:id="@+id/btn_mybutton"
android:layout_height="wrap_content"
android:layout_width="124dip"
android:layout_marginTop="5dip"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
Arcadia, just try the code below. There are several ways to get the result you're looking for, this is one of the easier ways.
ReplyDelete<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relative_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
>
<Button
android:id="@+id/the_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Centered Button"
/>
</RelativeLayout>
Setting the gravity of the RelativeLayout itself will affect all of the objects placed inside of it. In this case, it's just the button. You can use any of the gravity settings here, of course (e.g. center_horizontal, top, right, and so on).
You could also use this code below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relative_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="@+id/the_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Centered Button"
android:layout_centerInParent="true"
/>
</RelativeLayout>
You can use CENTER_IN_PARENT for relative layout
ReplyDelete