🤠

RecyclerViewでタグのフローレイアウト

2022/01/08に公開約1,600字

FlexboxLayoutManagerを設定することでタグのフローレイアウトを実現できるっぽい.
忘れそうなのでメモ.

install

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

implementation

SampleFragment.kt
class SampleFragment : Fragment(R.layout.fragment_sample) {
    companion object {
        fun newInstance() = SampleFragment()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val binding = FragmentSampleBinding.bind(view)
        val adapter = SampleAdapter()
        val context = requireContext()
        val hDivider = createDivider(context, LinearLayoutManager.HORIZONTAL)
        val vDivider = createDivider(context, LinearLayoutManager.VERTICAL)

        binding.recyclerView.apply {
            this.adapter = adapter
            this.layoutManager = FlexboxLayoutManager(requireContext()).apply {
                flexWrap = FlexWrap.WRAP
            }
            this.addItemDecoration(hDivider)
            this.addItemDecoration(vDivider)
        }

        val tags = (1..100).map { "Tag$it" }
        val items = tags.map(SampleViewHolder::Item)
        adapter.submitList(items)
    }

    private fun createDivider(context: Context, orientation: Int) =
        DividerItemDecoration(context, orientation).apply {
            ContextCompat.getDrawable(context, R.drawable.divider)
                ?.let(this::setDrawable)
        }
}

FlexboxManagerをlayoutManagerに設定しつつ、 flexWrap = FlexWrap.WRAP でいける.

view

screenshot

code

サンプル書いた!

Discussion

ログインするとコメントできます