Android Studio 3.0.1中ConstraintLayout四按钮权重一致设置问题
嗨,我来帮你排查下这个ConstraintLayout按钮权重不一致的问题!你只设置app:layout_constraintHorizontal_weight="1"却没生效,大概率是漏了两个关键配置,咱们一步步来修正:
核心问题分析&解决步骤
第一步:必须把按钮宽度设为
0dp
在ConstraintLayout中,权重是基于「可用剩余空间」来分配的,如果你给按钮设置了固定宽度(比如wrap_content或者具体数值),权重属性根本不会生效。所以每个按钮的android:layout_width必须改成:android:layout_width="0dp"第二步:确保按钮形成完整的水平约束链
权重只有在同一个约束链里才会起作用,你需要把四个按钮的横向约束互相连接,并且首尾按钮分别绑定到父布局的左右边界:- 第一个按钮:左约束连父布局
left,右约束连第二个按钮的left - 第二个按钮:左约束连第一个按钮的
right,右约束连第三个按钮的left - 第三个按钮:左约束连第二个按钮的
right,右约束连第四个按钮的left - 第四个按钮:左约束连第三个按钮的
right,右约束连父布局right
这样四个按钮就形成了一个完整的水平链,此时设置的
layout_constraintHorizontal_weight="1"才会让它们平分可用宽度。- 第一个按钮:左约束连父布局
示例修正后的XML代码片段
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- 第一个按钮 --> <Button android:id="@+id/btn1" android:layout_width="0dp" android:layout_height="wrap_content" android:text="按钮1" app:layout_constraintHorizontal_weight="1" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toLeftOf="@+id/btn2"/> <!-- 第二个按钮 --> <Button android:id="@+id/btn2" android:layout_width="0dp" android:layout_height="wrap_content" android:text="按钮2" app:layout_constraintHorizontal_weight="1" app:layout_constraintLeft_toRightOf="@+id/btn1" app:layout_constraintRight_toLeftOf="@+id/btn3"/> <!-- 第三个按钮 --> <Button android:id="@+id/btn3" android:layout_width="0dp" android:layout_height="wrap_content" android:text="按钮3" app:layout_constraintHorizontal_weight="1" app:layout_constraintLeft_toRightOf="@+id/btn2" app:layout_constraintRight_toLeftOf="@+id/btn4"/> <!-- 第四个按钮 --> <Button android:id="@+id/btn4" android:layout_width="0dp" android:layout_height="wrap_content" android:text="按钮4" app:layout_constraintHorizontal_weight="1" app:layout_constraintLeft_toRightOf="@+id/btn3" app:layout_constraintRight_toRightOf="parent"/> </android.support.constraint.ConstraintLayout>
额外注意点
如果设置后视觉上还是有细微差异,检查下有没有给按钮设置不同的minWidth、padding或者margin,把这些属性统一设置成相同值就能解决啦。
内容的提问来源于stack exchange,提问作者HelloCW
相关产品推荐
相关产品推荐

