在线性布局中居中按钮 [英] Center a button in a Linear layout

查看:29
本文介绍了在线性布局中居中按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用线性布局来显示一个漂亮的初始屏幕.它有 1 个按钮,应该水平和垂直居中在屏幕上.但是,无论我尝试做什么,按钮都会顶部对齐中心.我在下面包含了 XML,有人能指出我正确的方向吗?

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>

推荐答案

如果你想在屏幕中间居中一个项目,不要使用 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.

改用 RelativeLayout.

所以替换:

android:layout_gravity="center_vertical|center_horizontal"

对于相关的RelativeLayout 选项:

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>

这篇关于在线性布局中居中按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆