ConstraintLayout中Start与Left两类约束的具体区别是什么?
Left/Right 与 Start/End 约束的核心区别
- 方向属性类型不同:
Left/Right属于绝对方向约束,永远以屏幕物理左右侧为基准,不受系统语言布局方向影响;Start/End属于相对方向约束,会跟随系统布局方向自动调整:在从左到右(LTR,如中文、英文)的布局下Start=Left、End=Right,在从右到左(RTL,如阿拉伯语、希伯来语)的布局下Start=Right、End=Left,主要用于国际化多语言适配。 - 系统处理逻辑不同:高版本Android系统和
ConstraintLayout依赖默认优先适配相对方向规则,如果你使用的是ConstraintLayout 1.x旧版本,存在已知的Left/Right约束计算时额外叠加默认最小边距的bug,这就是你遇到的使用Left约束有细微间距、Start约束完全贴靠的原因。
需求实现方案
你需要仅让第一个ll_set靠左贴靠,保留另外两个LinearLayout位置不变,直接修改第一个控件的约束规则即可,两种方案可选:
方案1(推荐:无兼容性问题)
将ll_set的左约束替换为Start约束,同时如果你的应用不需要适配RTL布局,直接在AndroidManifest.xml的application节点添加android:supportsRtl="false",即可保证所有场景下Start永远等于Left,不会出现布局偏移:
<LinearLayout android:id="@+id/ll_set" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" <!-- 替换原来的Left约束 --> app:layout_constraintStart_toStartOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintRight_toLeftOf="@id/ll_weight" app:layout_constraintTop_toTopOf="parent">
方案2(快速适配,不改动其他逻辑)
直接给ll_set添加负左边距抵消多余的间隙即可,不需要调整其他控件的约束:
<LinearLayout android:id="@+id/ll_set" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginLeft="-8dp" <!-- 数值根据你实际的间隙大小调整 --> app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintRight_toLeftOf="@id/ll_weight" app:layout_constraintTop_toTopOf="parent">
另外建议你将ConstraintLayout的依赖版本升级到2.1.0及以上,可彻底解决旧版本的约束计算bug。
内容的提问来源于stack exchange,提问作者ybybyb
相关产品推荐
相关产品推荐

