我使用线性布局来显示一个相当轻的初始屏幕。它有一个按钮,应该是在屏幕的中心水平和垂直。然而,无论我尝试做什么,按钮将顶部对齐居中。我已经包括下面的XML,有人能指出我在正确的方向吗?

<?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>

当前回答

use

android: layout_centerHorizontal = " true "

其他回答

在按钮中设置为true android:layout_alignParentTop="true"和android:layout_centerHorizontal="true",如下所示:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
     <Button
        android:id="@+id/switch_flashlight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/turn_on_flashlight"
        android:textColor="@android:color/black"
        android:onClick="action_trn"
        android:background="@android:color/holo_green_light"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:padding="5dp" />
</RelativeLayout>

只需使用(使其位于布局的中心)

        android:layout_gravity="center" 

和使用

         android:layout_marginBottom="80dp"

         android:layout_marginTop="80dp"

改变位置

使用线性布局的中心:

<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>

在这种情况下,你也可以使用RelativeLayout作为ImageButton的父类

android:layout_centerInParent="true"

然后在ImageButton中使用上面的代码。

如果你想让一个项目在屏幕中间居中,不要使用线性布局,因为这意味着在一行中显示许多项目。

使用RelativeLayout代替。

所以更换:

android:layout_gravity="center_vertical|center_horizontal"

参阅相关的RelativeLayout选项:

android:layout_centerInParent="true"

所以你的布局文件看起来是这样的:

<?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>