flexbox-layout
flexbox-layout copied to clipboard
Simple spacing between item when flexWrap="wrap"?
Hi, im trying have a simple wrap layout
and I need to items to be spaced apart by sa certain value lets say 8dp. I might be blind but there is no way to achieve this?
I tried to workaround with a divider which only has size
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<size
android:width="8dp"
android:height="8dp" />
</shape>
This almost works, however has a side effect (bug?) where it makes items grow in height instead of putting them on a new line
Simply putting margins on each item manually wont work for me since Im adding views programatically and simply adding margins would cause doubling of inbetween margin; so I would need to figure out my its position and adjust with half margins accordingly. I believe this is layout's responsibility.
Thanks
Did you find any solution?
Adding the items programmatically can be a little persnickety. If you can get away with just setting top and bottom margin on all items then this can get you there. Android removes any margins when you add a view, so you have to programmatically set margin after you add the item to the layout.
tags.forEachIndexed { index, tagText ->
val view = itemView.context.layoutInflater.inflate(R.layout.tag, null)
view.tag.text = tagText
// add view
flexBoxTagLayout.addView(view)
// set margins after the fact
(view?.layoutParams as? ViewGroup.MarginLayoutParams)?.updateMargins(
bottom = itemView.context.resources.getDimensionPixelSize(R.dimen.tag_spacing),
right = itemView.context.resources.getDimensionPixelSize(R.dimen.tag_spacing)
)
}
If you using FlexboxLayoutManager
use this approach:
rv.layoutManager = FlexboxLayoutManager(context).apply {
alignItems = AlignItems.FLEX_START
}
val itemDecoration = FlexboxItemDecoration(context).apply {
setDrawable(ContextCompat.getDrawable(context, R.drawable.bg_divider))
setOrientation(FlexboxItemDecoration.HORIZONTAL)
}
if (rv.itemDecorationCount == 0) {
rv.addItemDecoration(itemDecoration)
}
bg_divider.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<size
android:width="8dp"
android:height="12dp" />
</shape>
Thanks, @yehezkiell! Also you can change orientation to setOrientation(FlexboxItemDecoration.BOTH)
.