Monday, 15 August 2022

Is it possible to have fixed number of columns with android flexbox layout

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>


from Is it possible to have fixed number of columns with android flexbox layout

No comments:

Post a Comment