错误Circular dependencies cannot exist in RelativeLayout

问题描述

日前在检查crash日志时发现了如下的错误:

java.lang.IllegalStateException: Circular dependencies cannot exist in RelativeLayout
问题分析

错误日志提示是在RelativeLayout中存在了循环依赖导致的。

所谓的循环依赖其实就是指的互相定位。在RelativeLayout这一相对布局中,我们需要设定一个View针对另外的View的相对位置,也就是需要至少一个View作为基准被另外的View进行相对位置设定,如果两个View互为基准View,系统就难以去定位两个View的位置,就会报错。

举个例子进行说明:
存在两个View:ViewA和ViewB,需要设定ViewB在ViewA的下方,那我们只需要在ViewB里面添加layout_below:ViewA即可,如果采用如下的写法,设置ViewA在ViewB的上方,同时设置ViewB在ViewA的下方,就会造成循环依赖,导致系统错误:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:textSize="30sp"
        android:background="@color/cardview_light_background"
        android:id="@+id/btn1_test_fragment"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_above="@+id/tv_test1"
        android:text="这里是新UI" />

    <TextView
        android:layout_below="@+id/btn1_test_fragment"
        android:id="@+id/tv_test1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</RelativeLayout>

如上方代码同时设置两个View互相以对方为基准View就会报错。

解决办法

只需要破除循环依赖状态即可,使得View之间不互相定位依赖即可。例如上述代码中只需要去掉layout_above或者layout_below属性即可。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值