FlexboxLayout,可以很方便地实现瀑布流的效果。今天正好用到项目中。
先看效果图
20201127083739.png

1.添加依赖

implementation 'com.google.android:flexbox:2.0.1'

2.代码

val manager = FlexboxLayoutManager(this)
        manager.flexDirection = FlexDirection.ROW
        manager.flexWrap = FlexWrap.WRAP
        recyclerView.layoutManager = manager
        val decoration = FlexboxItemDecoration(this)
        val drawable = GradientDrawable().apply {
            setSize(DisplayUtils.dip2px(this@SearchActivity, 8f), DisplayUtils.dip2px(this@SearchActivity, 8f))
        }
        decoration.setDrawable(drawable)
        decoration.setOrientation(FlexboxItemDecoration.BOTH)
        recyclerView.addItemDecoration(decoration)
        recyclerView.adapter = adapter

在Adapter中填充每一行的剩余空间

val params = holder.text1.layoutParams
        if (params is FlexboxLayoutManager.LayoutParams) {
            val fbLayoutManager = holder.text1.layoutParams as FlexboxLayoutManager.LayoutParams
            fbLayoutManager.flexGrow = 1.0f
        }

3.总结

FlexboxLayout+RecyclerView可以实现自动换行的效果,不需要指定列数,可以实现自动换行,以上只是一些简单的使用。