首页 > 解决方案 > RelativeLayout 中的元素排列

问题描述

有一个xml文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/password"
        android:layout_centerHorizontal="true"
        android:hint="@string/loginText"
        android:layout_marginBottom="20dp"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button"
        android:hint="@string/passwordText"
        android:layout_marginBottom="20dp"
        android:inputType="textPassword"
        />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</RelativeLayout>

当我运行程序时,我收到以下错误:

E/AndroidRuntime: FATAL EXCEPTION: main Process: asus.example.com.oop, PID: 5020 java.lang.IllegalStateException: 循环依赖不能存在于RelativeLayout

怎么了?登录在密码上方,密码在按钮上方。我不明白为什么会有循环依赖

标签: androidandroid-layoutandroid-relativelayout

解决方案


解决方案

而不是使用layout_above它将是一个不错的选择layout_below

像这样:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="0dp"
        android:layout_marginBottom="20dp"
        android:hint="Hello"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/login"
        android:hint="Password"
        android:text="Hello"
        android:layout_marginBottom="20dp"
        android:inputType="textPassword"
        />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hello"
        android:layout_below="@+id/password"/>

</RelativeLayout>

试试看,希望对你有帮助。


推荐阅读