將線性佈局中的按鈕居中

我使用線性佈局來顯示很是輕的初始屏幕。 它有一個按鈕,應該在屏幕中水平和垂直居中。 但不管我嘗試作什麼,按鈕都會在頂部對齊中心。 我已經包含了下面的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>
相關文章
相關標籤/搜索