android - 居中对齐的登录屏幕

标签 android android-layout

我想设计一个登录界面。内容应水平和垂直居中。到目前为止,我已经创建了这个:

enter image description here

目前我已经将 marginTop 赋予了我的顶部元素,即图标。但我认为这不是正确的方法。我希望用户名字段位于屏幕的垂直中心。这会将整个内容移动到屏幕中间。

到目前为止,这是我的布局代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LoginActivity" 
    android:background="#d1d6df">

    <ImageView 
        android:id="@+id/imgIcon"
        android:src="@drawable/ic_launcher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="Icon"
        android:layout_marginBottom="20dp"
        android:layout_marginTop="120dp"
        android:layout_centerHorizontal="true"/>

    <EditText
        android:id="@+id/txtUsername"
        android:hint="Username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/imgIcon"
        android:ems="10"
        android:inputType="text">

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/txtPassword"
        android:hint="@string/passwordHint"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/txtUsername"
        android:ems="10"
        android:inputType="textPassword">
    </EditText>

    <Button
        android:text="@string/loginButtonText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/txtPassword"
        />

</RelativeLayout>

此外,我还希望登录按钮从其上级兄弟(即密码字段)获取宽度。这可能吗?

最佳答案

  1. 删除 marginTop 并在 relativeLayout 上添加 android:gravity="center"
  2. android:layout_alignLeft="@+id/txtPassword"android:layout_alignRight="@+id/txtPassword" 添加到您的按钮

希望这对你有帮助:)

关于android - 居中对齐的登录屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14362648/

相关文章:

android - 使用 mGLSurfaceView 处理 UI 事件

Android 将字节码转换为 dex : Cause: Dex cannot parse version 52 byte code 时出错

Android OkHttp,刷新过期 token

java - Android 平台中布局和代码之间的独立性

带有叠加层的 Android 可缩放/可滚动 ImageView

android - 横向纵向

android - 在包 'layout_weightSum' 中找不到属性 'android' 的资源标识符

java.lang.NoClassDefFoundError : Failed resolution of: Ljavax/naming/directory/InitialDirContext; 错误

android - 我的布局文件没有显示在 setContent(R.layout.xml 文件)..?

java - 将 LinearLayout 调整为 ImageView 的宽度