当前位置: 首页 > news >正文

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>(</
http://www.dtcms.com/a/337919.html

相关文章:

  • Android输入框文字不垂直居中
  • Maven Shade Plugin 插件使用说明
  • 【音视频】ISP能力
  • 阿里云odps和dataworks的区别
  • 多数据源 Demo
  • 机器学习之数据预处理(二)
  • HBM CPU Cache / GPU Cache 的关系
  • 第一阶段C#-14:委托,事件
  • ubuntu 下载安装tomcat简单配置(傻瓜式教程)
  • minio安装和配置
  • JUC读写锁
  • 视觉语言导航(7)——VLN的数据集和评估方法 3.2
  • openfeign 只有接口如何创建bean的
  • C++多线程编程深度解析【C++进阶每日一学】
  • 【损失函数】完全解析(两万字解读)
  • 现有网络模型的使用及修改
  • 一般情况下,python函数都会返回对象,但有时只调用一个函数,这是在修改这个信息
  • CAG缓存增强生成与RAG检索增强生成对比
  • CAG缓存检索生成 案例流程
  • 04高级语言逻辑结构到汇编语言之逻辑结构转换 do...while 结构
  • Android Studio受难记
  • echarts实现3个y轴的图表
  • 传输层协议——TCP
  • 刺猬的开发笔记之企业级兑换奖励c端链路开发
  • 【图论 次短路】P1491 集合位置|省选-
  • 【typenum】 17 非负数标记
  • Ansible 部署LNMP
  • shell脚本实现读取ini键值
  • 部署过程 99年证书
  • Servlet上传文件