ConstraintLayout 1.1.0双向同边约束失效问题咨询
问题根源与解决方案
嘿,这个问题我之前也碰到过,核心原因不是双向约束本身,而是你布局里的重复命名空间加上ConstraintLayout 1.1.0版本的解析逻辑变化导致的。
具体原因:
- 你在布局顶部同时声明了
app和app1两个命名空间,但它们都指向同一个http://schemas.android.com/apk/res-auto路径。ConstraintLayout 1.0.2对这种重复命名空间的约束解析比较宽松,能正常处理;但1.1.0版本对约束的冲突检测和解析做了严格化优化,当同一个约束关系被两个不同命名空间的属性重复定义时,会触发约束系统的异常,最终导致所有约束效果失效。 - 你想实现的
viewOne与viewTwo的双向垂直约束本身是合理的,但错误地用了两个不同的命名空间来声明,这才是问题的导火索。
正确的写法:
只需要用同一个命名空间(比如统一用app)来声明双向约束即可,1.1.0版本下完全正常:
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto"> <TextView android:id="@+id/viewOne" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toTopOf="@+id/viewTwo" tools:text="View one"/> <TextView android:id="@+id/viewTwo" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintTop_toBottomOf="@+id/viewOne" tools:text="View two"/> </android.support.constraint.ConstraintLayout>
额外排查建议:
- 检查所有布局文件,避免重复声明指向同一资源路径的命名空间;
- 升级ConstraintLayout版本后,尽量遵循官方规范的约束写法,不要依赖旧版本的宽松解析逻辑;
- 如果遇到约束异常,建议先简化布局,逐步添加约束来快速定位冲突点。
内容的提问来源于stack exchange,提问作者Jacob Ferrero
相关产品推荐
相关产品推荐

