1. 核心属性说明
纵向间距(水平排列时,子项左右间距)
app:showDividerVertical="middle":只在子项之间显示
app:dividerDrawableVertical="@drawable/spacing_16dp":纵向间距 Drawable
横向间距(换行时,行与行之间的上下间距)
app:showDividerHorizontal="middle":只在行之间显示
app:dividerDrawableHorizontal="@drawable/spacing_8dp":横向间距 Drawable
2. 完整示例
<com.google.android.flexbox.FlexboxLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:flexDirection="row"
app:flexWrap="wrap"
<!-- 纵向(子项左右)间距 16dp -->
app:showDividerVertical="middle"
app:dividerDrawableVertical="@drawable/spacing_16dp"
<!-- 横向(行之间)间距 8dp -->
app:showDividerHorizontal="middle"
app:dividerDrawableHorizontal="@drawable/spacing_8dp">
<!-- 子项 -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="标签1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="标签2"/>
<!-- 更多子项... -->
</com.google.android.flexbox.FlexboxLayout>
3. 间距 Drawable 定义(drawable/spacing_16dp.xml)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- 透明,仅占空间 -->
<solid android:color="@android:color/transparent"/>
<!-- 纵向间距:宽度 = 16dp,高度任意 -->
<size android:width="16dp" android:height="1dp"/>
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@android:color/transparent"/>
<!-- 横向间距:高度 = 8dp,宽度任意 -->
<size android:width="1dp" android:height="8dp"/>
</shape>
二、代码动态设置
FlexboxLayout flexboxLayout = findViewById(R.id.flexbox);
// 纵向间距(子项左右)
flexboxLayout.setShowDividerVertical(FlexboxLayout.SHOW_DIVIDER_MIDDLE);
flexboxLayout.setDividerDrawableVertical(
ContextCompat.getDrawable(this, R.drawable.spacing_16dp));
// 横向间距(行之间)
flexboxLayout.setShowDividerHorizontal(FlexboxLayout.SHOW_DIVIDER_MIDDLE);
flexboxLayout.setDividerDrawableHorizontal(
ContextCompat.getDrawable(this, R.drawable.spacing_8dp));