Android 流式布局实现方案全解析
在日常 Android 开发中,经常会遇到 流式布局 (Flow Layout) 的需求,比如:
- 搜索历史标签
- 电商商品属性选择(颜色 / 尺寸)
- 新闻应用的标签推荐
- 话题、标签云
所谓“流式布局”,就是子 View 按行排列,如果一行放不下,就自动换行,类似于 HTML/CSS 的 flex-wrap: wrap 效果。
那么在 Android 中,如何实现流式布局呢?
1. FlexboxLayout(推荐)
Google 官方开源的 FlexboxLayout 是实现流式布局的首选,它模仿了 CSS 的 Flexbox,支持换行、对齐、弹性伸缩等特性。
引入依赖:
dependencies {implementation 'com.google.android.flexbox:flexbox:3.0.0'
}
对应的仓库地址:
https://github.com/google/flexbox-layout
使用示例
<com.google.android.flexbox.FlexboxLayoutandroid:id="@+id/flexboxLayout"android:layout_width="match_parent"android:layout_height="wrap_content"app:flexWrap="wrap"app:justifyContent="flex_start"app:alignItems="flex_start"android:padding="8dp"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="4dp"android:background="@drawable/bg_tag"android:text="标签1"/>
</com.google.android.flexbox.FlexboxLayout>
动态添加
val flexboxLayout = findViewById<FlexboxLayout>(R.id.flexboxLayout)fun addTag(text: String) {val tv = TextView(this).apply {this.text = textsetPadding(24, 12, 24, 12)background = ContextCompat.getDrawable(context, R.drawable.bg_tag)}flexboxLayout.addView(tv)
}
✅ 优点:官方维护,功能完善,属性和 CSS 一致,上手快
❌ 缺点:标签数量过多时性能一般
2. RecyclerView + FlexboxLayoutManager
如果标签数量较多,或者需要复用机制(如搜索历史、标签云),推荐用 RecyclerView 搭配 FlexboxLayoutManager
使用示例
val layoutManager = FlexboxLayoutManager(this).apply {flexWrap = FlexWrap.WRAPflexDirection = FlexDirection.ROWjustifyContent = JustifyContent.FLEX_START
}
recyclerView.layoutManager = layoutManager
recyclerView.adapter = TagAdapter(tagList)
适配器:
class TagAdapter(private val data: MutableList<String>) :RecyclerView.Adapter<TagAdapter.TagViewHolder>(</