将线性布局中的按钮居中

我使用线性布局来显示很是轻的初始屏幕。 它有一个按钮,应该在屏幕中水平和垂直居中。 但不管我尝试作什么,按钮都会在顶部对齐中心。 我已经包含了下面的XML,有人能指出我正确的方向吗? android

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

#1楼

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

#2楼

您能够使用RelativeLayoutspa


#3楼

使用相对布局会更容易,但对于线性布局,我一般经过确保宽度与父级匹配来居中: code

android:layout_width="match_parent"

而后相应地给予左右边距。 xml

android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"

#4楼

您是否尝试在布局中定义android:gravity="center_vertical|center_horizontal"并在图像中设置android:layout_weight="1"utf-8


#5楼

若是要将项目置于屏幕中间的中心,请不要使用LinearLayout由于这些项目用于显示连续的多个项目。 get

请改用RelativeLayoutit

因此替换: io

android:layout_gravity="center_vertical|center_horizontal"

对于相关的RelativeLayout选项: coding

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>
相关文章
相关标签/搜索