之前使用 FlexboxLayout 实现流式布局,但是选中和反选效果不好实现,就改用RecyclerView+FlexboxLayoutManager 实现流式布局:
说明:如果是直接展示标签,没有其他选中效果时,建议直接使用 FlexboxLayout实现:
<!-- <com.google.android.flexbox.FlexboxLayout-->
<!-- android:id="@+id/flexbox"-->
<!-- android:layout_width="match_parent"-->
<!-- app:flexWrap="wrap"-->
<!-- android:layout_height="wrap_content"-->
<!-- android:layout_marginStart="@dimen/sp_24"/>-->
导入依赖库:
implementation 'com.google.android.flexbox:flexbox:3.0.0'
@Route(path = RouterPath.helpCenterPath)
class HelpCenterActivity : BaseActivity() {
private lateinit var binding: ActivityHelpCenterBinding
private var lastPosition = -1
private lateinit var mAdapter: BaseQuickAdapter<TagInfo, BaseViewHolder>
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityHelpCenterBinding.inflate(layoutInflater)
setContentView(binding.root)
super.onCreate(savedInstanceState)
showTag()
}
private fun showTag() {
val list = mutableListOf<TagInfo>()
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<TagInfo, BaseViewHolder>(R.layout.item_new_function) {
override fun convert(holder: BaseViewHolder, item: TagInfo) {
holder.setText(R.id.tv_tag, item.text)
val rlItem = holder.getView<RelativeLayout>(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<TagInfo> = 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,
)
}