需要帮助将 EditText 在线性布局中居中
我试图将编辑文本在线性布局中垂直和水平居中,但它不起作用。真的很简单的问题。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@drawable/login">
<EditText
android:layout_width="150dp"
android:layout_height="wrap_content"
android:background="@drawable/loginbutton"
android:text="Username"
android:layout_gravity="center"
android:textSize="25dp"
android:gravity="center_horizontal|center_vertical"
android:textColor="#000000"
android:layout_margin="10dp"
android:id="@+id/username">
</EditText>
同时我会尝试更改为相对布局。
I'm trying to center an edittext vertically and horizontally in a linear layout, but it is not working. Very simple problem really.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@drawable/login">
<EditText
android:layout_width="150dp"
android:layout_height="wrap_content"
android:background="@drawable/loginbutton"
android:text="Username"
android:layout_gravity="center"
android:textSize="25dp"
android:gravity="center_horizontal|center_vertical"
android:textColor="#000000"
android:layout_margin="10dp"
android:id="@+id/username">
</EditText>
I'll try changing to a relativelayout in the mean time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
据我所知,LinearLayout 不支持在堆叠项目的方向上居中。除非
LinearLayout
至关重要(在您的情况下不应该如此,因为您还需要居中),否则我建议您切换到RelativeLayout
。使用
RelativeLayout
,您可以在EditText
上设置属性android:layout_centerInParent="true"
以使其居中。LinearLayout
do not support centering in the direction it stacks items as far as I know. Unless theLinearLayout
is crucial (which in your case it shouldn't be, as you also need the centering), I would recommend you switch to aRelativeLayout
.With a
RelativeLayout
, you can set the attributeandroid:layout_centerInParent="true"
on theEditText
to get it centred.使用重力会影响所述 UI 项目内容的重力,这意味着(在本例中)EditText 内的文本将居中。为了使 UI 项目本身居中,您需要定义layout_gravity,因为这是 UI 项目在其父项中所具有的重力。 OP发布的代码将进行水平居中,但不会进行垂直居中。
作为替代方案,您可以使用RelativeLayout
Using gravity affects the gravity of the contents of said UI item, this means (in this case) that the text inside the EditText would be centered. In order to center the UI item itself you need to define layout_gravity as this is the gravity a UI item holds within his parent. The code posted by the OP will do the horizontal center but not the vertical center.
As an alternative you can use RelativeLayout
这很简单。添加带有线性布局的 android:gravity="center" 。
It is very simple. Add android:gravity="center" with the linear layout.
试试这个:
Try this: