I'm fetching a list from my API of for example 25 tags of country such as, Germany, England, France, Italy etc...
I'd like to have 2 row with 10 chips
per row, and if I get 30 tags the next time I fetch I want to have 3 row of 10 chips
etc...
So far I haven't found anything allowing me to do that. I've taken a quick look at Flexbox-Layout
but it doesn't seem to fit my needs, I currently have the code below, but I was thinking of doing such logic with a Recyclerview
Fragment
viewModel.videoSelected.observe(viewLifecycleOwner, object : Observer<VideoPage> {
override fun onChanged(videoPage: VideoPage?) {
videoPage?.tags ?: return
val chipGroup = binding.chipGroup
val chipGroupInflater = LayoutInflater.from(chipGroup.context)
val children = videoPage.tags.map { tagName ->
val chip = chipGroupInflater.inflate(R.layout.chip_video_tag, chipGroup, false) as Chip
chip.text = tagName
chip.tag = tagName
chip.setOnClickListener {
Toast.makeText(context, tagName, Toast.LENGTH_SHORT).show()
}
chip
}
for (chip in children) {
chipGroup.addView(chip)
}
}
})
and the result is the 25 chips in one line. How can I make it so that it's divide on multiple line ?
I've also manage to do it in a more simple way with BindingAdapter
:
<androidx.recyclerview.widget.RecyclerView
app:listVideoTagChip="@{viewModel.videoSelected.tags}"
android:id="@+id/rv_video_chips"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="androidx.recyclerview.widget.StaggeredGridLayoutManager"
android:orientation="horizontal"
tools:listitem="@layout/chip_video_tag"/>
private const val TAG_PER_ROW = 10
@BindingAdapter("listVideoTagChip")
fun RecyclerView.bindRecyclerView(data: List<String>?) {
val adapter: VideoTagAdapter = this.adapter as VideoTagAdapter
(layoutManager as StaggeredGridLayoutManager).spanCount =
data?.size?.let {
ceil(it.toDouble().div(TAG_PER_ROW)).toInt()
} ?: 1
adapter.submitList(data)
}