我使用线性布局来显示非常轻的初始屏幕 . 它有一个按钮,应该在屏幕中水平和垂直居中 . 但无论我尝试做什么,按钮都会在顶部对齐中心 . 我已经包含了下面的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>
18 回答
如果您想将项目置于屏幕中间,请不要使用
LinearLayout
,因为它们用于连续显示多个项目 .请改用RelativeLayout .
所以替换:
对于相关的
RelativeLayout
选项:所以你的布局文件看起来像这样:
使用LinearLayout进行中心:
您是否尝试在布局中定义
android:gravity="center_vertical|center_horizontal"
并在图像中设置android:layout_weight="1"
?使用线性布局的常用方法是在图像按钮上设置属性
您可以选择是在线性布局中左对齐,居中对齐还是右对齐每个对象 . 注意上面的行与之完全相同
加上这个
在LinearLayout中 .
这很容易
你可以使用
RelativeLayout
.上面的代码将起作用 .
来自我的机器的完整和可用的样品......
根据android:layout_gravity的XML属性的Android文档,我们可以轻松地做到:)
如果您使用
LinearLayout
,则可以添加重心:您也可以尝试此代码:
只需使用(使其位于布局的中心)
并使用
改变位置
在Button中设置为true
android:layout_alignParentTop="true"
和android:layout_centerHorizontal="true"
,如下所示:您还可以将LinearLayout的宽度设置为
wrap_content
并使用android:layout_centerInParent
,android:layout_centerVertical="true"
:你试过这个吗?
使用
使用相对布局会更容易,但对于线性布局,我通常会确保宽度与父级相匹配:
然后相应地给出左右边距 .