How do I center all my RecyclerView
items using the FlexboxLayoutManager
?
I need the items to be centered like this:
My code where I set the layout manager:
val layoutManager = FlexboxLayoutManager(this)
layoutManager.setFlexWrap(FlexWrap.WRAP)
layoutManager.setFlexDirection(FlexDirection.ROW)
layoutManager.setJustifyContent(JustifyContent.FLEX_START)
layoutManager.setAlignItems(AlignItems.FLEX_START)
val adapter = TagAdapter(tags)
tagRecyclerView.adapter = adapter
tagRecyclerView.layoutManager = layoutManager
(I tried to set layoutManager.setAlignItems(AlignItems.FLEX_START
) to layoutManager.setAlignItems(AlignItems.CENTER)
however it did not work...
Try this
Short answer
You are using
layoutManager.setAlignItems(AlignItems.FLEX_START)
. This is causing start alignment.You should use one of below two alignment that suits your requirement.
layoutManager.setAlignItems(AlignItems.CENTER)
.or
layoutManager.setAlignItems(AlignItems.SPACE_AROUND)
.Note:
Because you said this
Keep you item layout width
wrap_content
. (all child with parent should havewrap_content
width.) likeandroid:layout_width="wrap_content"
If you use
match_parent
width then you will not get centered items.