Center a button in a Linear layout
I am using a linear layout to display a pretty light initial screen. It has 1 button that is supposed to centre in the screen both horizontally and vertically. However no matter what I try to do the button will top align centre. I have included the XML below, can some one point me in the right direction?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageButton android:id="@+id/btnFindMe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:background="@drawable/findme"></ImageButton>
</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>
使用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>
你有没有尝试在图像中定义android:gravity="center_vertical|center_horizontal"
在其中设置android:layout_weight="1"
?
上一篇: 我可以在android布局中加下文字吗?
下一篇: 将按钮置于线性布局中