前言
Compose库中是没有原生的类似FlowLayout的布局的
于是我们来自己实现一个FlowLayout
正文
FlowLayout
先看看FlowLayout实现的效果:
代码很简单:
看一下api:
/**
* 可以自动换行的线性布局
* [modifier]修饰
* [orientation]排列的方向,[Orientation.Horizontal]时会先横向排列,一排放不下会换到下一行继续横向排列
* [horizontalAlignment]子级在横向上的位置
* [verticalAlignment]子级在竖向上的位置
* [horizontalMargin]子级与子级在横向上的间距
* [verticalMargin]子级与子级在竖向上的间距
* [maxLines]最多能放多少行(或列)
* [content]compose内容区域
*/
@Composable
fun FlowLayout(
modifier: Modifier = Modifier,
orientation: Orientation = Orientation.Horizontal,
horizontalAlignment: Alignment.Horizontal = Alignment.Start,
verticalAlignment: Alignment.Vertical = Alignment.Top,
horizontalMargin: Dp = 0.dp,
verticalMargin: Dp = 0.dp,
maxLines: Int = Int.MAX_VALUE,
content: @Composable () -> Unit
)
原理:
原理其实和安卓xml布局中的FlowLayout一样,就是测量所有的子项,并根据方向,间距,对齐方式对子项进行测量和放置即可
引入项目
在根项目的build.gradle文件中加入:
allprojects {
repositories {
maven { url 'https://jitpack.io' }
...
}
}
app的build.gradle中加上,最新版本参考:JitPack | Publish JVM and Android libraries
dependencies{
...
implementation 'com.github.ltttttttttttt:ComposeViews:1.1.4'
}
然后就可以愉快的使用FlowLayout了
项目已开源,欢迎star:GitHub - ltttttttttttt/ComposeViews
并且项目中不止有FlowLayout,还有更多好用的Compose组件,比如:
ComposePager
Banner
GoodTextField和PasswordTextField
后续还会添加更多的Compose组件
end