I am trying to replace my existing GridLayout with flexbox layout. I have a layout that requires me to have exactly 4 columns and two rows.
Only way I have found this to work is by code
val rootFlexboxLayout = binding.moreActionLayout
rootFlexboxLayout.flexDirection = FlexDirection.ROW
rootFlexboxLayout.justifyContent = JustifyContent.FLEX_START
rootFlexboxLayout.alignContent = AlignContent.FLEX_START
rootFlexboxLayout.alignItems = AlignItems.STRETCH
rootFlexboxLayout.flexWrap = FlexWrap.WRAP
val flexboxLayoutParams: FlexboxLayout.LayoutParams = FlexboxLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
flexboxLayoutParams.flexBasisPercent = 0.23f
// Manually create views to be added to flexbox layout
tabs.forEachIndexed { index, tabViewState ->
// Add the tab to the layout
val tabView = BottomBarTabView(requireContext())
tabView.apply {
id = View.generateViewId()
layoutParams = flexboxLayoutParams
}
binding.moreActionLayout.addView(tabView, index)
}
Thing that is bothering me is magic number of 0.23f is the only thing that gets me 4 columns, if I set to 0.25 (25%) it gives me 3 columns.
My layout definition for moreActionLayout looks like this:
<com.google.android.flexbox.FlexboxLayout
android:id="@+id/moreActionLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:alignContent="flex_start"
app:alignItems="center"
app:flexWrap="wrap"
app:flexDirection="row"
android:padding="8dp">
</com.google.android.flexbox.FlexboxLayout>
As I am new to android, I had to study Flex layout but seeing attributes of flex layout with identical names I got confused. This is what I did.
I might be wrong in interpreting these attributes. I found two attributes applicable to your query i.e
From documentation , layout_minWidth
layout_maxWidth
So,I guess, just applying flexiWrap attribute to wrap in flexlayout and for children's applying maxWidth or minWidth to a value , you can achieve solution to your query. To get the value of maxWidth in particular orientation, calculation is
This method returns maxWidth a child can have for given x columns. As you are adding views programmatically, you can set the layout parameters on the child view to have this maxWidth or just set the width. For different orientation, you ought to call this method in onResume() and load the views again which is kind of bad but it depends upon the no. of views to be load.