Center a button in a Linear layout
Center using a LinearLayout:
<LinearLayout
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<ImageButton
android:id="@+id/btnFindMe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/findme" />
</LinearLayout>
If you want to center an item in the middle of the screen don't use a LinearLayout
as these are meant for displaying a number of items in a row.
Use a RelativeLayout
instead.
So replace:
android:layout_gravity="center_vertical|center_horizontal"
for the relevant RelativeLayout
option:
android:layout_centerInParent="true"
So your layout file will look like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageButton android:id="@+id/btnFindMe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@drawable/findme"></ImageButton>
</RelativeLayout>
Have you tried defining android:gravity="center_vertical|center_horizontal"
inside the layout and setting android:layout_weight="1"
in the image?
A commonly-used method that works with linear layout is to set a property on the image button
android:layout_gravity="center"
You can choose whether to left-align, center-align, or right-align each object in the linear layout. Note that the above line is precisely the same as
android:layout_gravity="center_vertical|center_horizontal"
Add this
android:gravity="center"
In LinearLayout.