RecyclerView+Flexbox实现流式布局

之前使用 FlexboxLayout 实现流式布局,但是选中和反选效果不好实现,就改用RecyclerView+FlexboxLayoutManager 实现流式布局:

说明:如果是直接展示标签,没有其他选中效果时,建议直接使用 FlexboxLayout实现:







导入依赖库:

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

RecyclerView+Flexbox实现流式布局_第1张图片

@Route(path = RouterPath.helpCenterPath)
class HelpCenterActivity : BaseActivity() {
    private lateinit var binding: ActivityHelpCenterBinding
    private var lastPosition = -1
    private lateinit var mAdapter: BaseQuickAdapter
 
    override fun onCreate(savedInstanceState: Bundle?) {
        binding = ActivityHelpCenterBinding.inflate(layoutInflater)
        setContentView(binding.root)
        super.onCreate(savedInstanceState)
        showTag()
    }

    private fun showTag() {
        val list = mutableListOf()
        for (i in 0..8) {
            list.add(TagInfo("Type${i + 1}", "${i + 1}", false))
        }
        with(binding.rvTag) {
            layoutManager = FlexboxLayoutManager(context, FlexDirection.ROW, FlexWrap.WRAP)

            mAdapter = object :
                BaseQuickAdapter(R.layout.item_new_function) {
                override fun convert(holder: BaseViewHolder, item: TagInfo) {

                    holder.setText(R.id.tv_tag, item.text)

                    val rlItem = holder.getView(R.id.ll_root)
                    if (item.isSelect) {
                        rlItem.background =
                            getDrawable(R.drawable.shape_stroke_00d1d3_solid_black_3_radius8)
                    } else {
                        rlItem.background = getDrawable(R.drawable.shape_black_3_radius8)
                    }
                }
            }
            mAdapter.setOnItemClickListener { adapter, view, position ->
                setSelected(position)
                val itemBean = adapter.getItem(position)
                if (itemBean is TagInfo) {
                    ToastUtils.showShort("选择了${itemBean.type}")
                }
            }
            mAdapter.setNewInstance(list)
            adapter = mAdapter
            setSelected(0)
        }
    }

    private fun setSelected(position: Int) {
        val list: MutableList = mAdapter.data
        // 选中
        list[position].isSelect = true
        mAdapter.notifyItemChanged(position)
        // 取消选中
        if (lastPosition > -1 && lastPosition < list.size) {
            list[lastPosition].isSelect = false
            mAdapter.notifyItemChanged(lastPosition)
        }
        lastPosition = position
    }

    data class TagInfo(
        var text: String,
        var type: String,
        var isSelect: Boolean = false,
    )
}

你可能感兴趣的:(代码块,Flexbox,流式布局)