Android FlexboxLayout 按钮水平间距设置与垂直堆叠顺序调整问题
水平排列的间距问题
给单个按钮加margin、调整justifyContent都不生效的核心原因是你给两个按钮都设置了app:layout_flexGrow="1",子元素会自动平分主轴所有剩余空间,justifyContent只在子元素总宽度小于容器宽度时才会生效,单边margin也会被计入子元素的宽度计算,折行时自然会出现宽度不均的问题。
直接在根FlexboxLayout上添加两个间距属性即可,不需要修改子按钮的属性:
app:gap="16dp" <!-- 水平同行时两个按钮的中间间距,容器首尾不会留多余边距 --> app:flexCrossGap="12dp" <!-- 折行垂直排列时,上下两行按钮的间距 -->
这两个属性是FlexboxLayout原生提供的间距控制能力,会自动根据排列状态在元素之间插入间距,不会干扰flexGrow的宽度计算逻辑,完美适配横、竖两种排列场景。
如果你的flexbox依赖版本低于2.1.0不支持gap属性,可以换用divider方案:给FlexboxLayout设置
android:showDivider="middle",传入一个固定宽/高的透明shape作为divider,也能实现同等效果,不会出现margin的计算问题。
垂直堆叠时的顺序调整
如果要实现「水平排列时Clear在左、Apply在右,垂直堆叠时Apply在上、Clear在下」的效果,不需要修改XML里的按钮书写顺序,只需要给Apply按钮添加app:layout_order="-1"属性即可:
<Button android:id="@+id/apply" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Apply" app:layout_flexGrow="1" app:layout_order="-1" />
FlexboxLayout的子元素默认layout_order值为0,数值越小排列优先级越高。设置为-1后,空间不足折行时Apply会优先占据上方的行位置;水平排列时两个按钮可以放在同一行,不会改变原有左右顺序。
如果你不需要保留水平状态的原有顺序,直接调换两个按钮在XML中的书写位置,或者给FlexboxLayout设置app:flexDirection="row_reverse"也能实现垂直状态下Apply在上的效果,但这两种方式会同步改变水平排列时的按钮顺序,按需选择即可。
修改后的完整可用布局代码:
<com.google.android.flexbox.FlexboxLayout android:layout_width="match_parent" android:layout_height="wrap_content" app:flexWrap="wrap" app:gap="16dp" app:flexCrossGap="12dp" > <Button android:id="@+id/clear" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Clear" app:layout_flexGrow="1" style="?attr/materialButtonOutlinedStyle" /> <Button android:id="@+id/apply" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Apply" app:layout_flexGrow="1" app:layout_order="-1" /> </com.google.android.flexbox.FlexboxLayout>
内容的提问来源于stack exchange,提问作者pepperlove

