我正在尝试在线性布局中垂直和水平居中编辑文本,但它不起作用。非常简单的问题。
<?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>
我会尝试同时改为相对布局。
答案 0 :(得分:11)
LinearLayout
不支持以堆叠项目为中心。除非LinearLayout
至关重要(在您的情况下它不应该,因为您还需要居中),我建议您切换到RelativeLayout
。
使用RelativeLayout
,您可以在android:layout_centerInParent="true"
上设置属性EditText
,使其居中。
答案 1 :(得分:1)
使用重力影响所述UI项目内容的重力,这意味着(在这种情况下)EditText内的文本将居中。为了使UI项目本身居中,您需要定义layout_gravity,因为这是UI项目在其父项目中的重力。 OP发布的代码将执行水平中心,而不是垂直中心。
作为替代方案,您可以使用RelativeLayout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/login"
android:orientation="vertical" >
<EditText
android:id="@+id/username"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="@drawable/loginbutton"
android:layout_centerInParent="true"
android:text="Username"
android:textColor="#000000"
android:textSize="25dp" >
</EditText>
</RelativeLayout>
答案 2 :(得分:1)
很简单。使用线性布局添加 android:gravity =“center”。
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
>
答案 3 :(得分:1)
LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/login"
android:gravity="center"
答案 4 :(得分:-1)
试试这个:
<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"
android:layout_centerVertical="true"
android:layout_centerInParent="true">