androidgridlayoutmanager

Can I set the width of a column in percents in GridLayoutManager?


I have an alert dialog that contains a RecyclerView. Each item in the recycler is a simple checkbox. I need to draw it in three columns.

For this I use GridLayoutManager

layoutManager = GridLayoutManager(context, 3, GridLayoutManager.HORIZONTAL, false)

What I see is in a result is this

enter image description here

Not bad. The problem is that I need to set every column's width to 33% of the width of my dialog. I don't have any fixed width of my checkbox in pixels as text can vary. Here's a layout used for the recycler.

<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>
        <variable name="item" type="..." />
    </data>

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="@={item.enabled}"
        android:text="@{item.name}"
        android:minWidth="40dp"/>

</layout>

My Recycler is created with the width equals to parent

 <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

Any ideas how to set width in percents?


Solution

  • If your RecyclerView is laid out correctly, You can force ViewHolder size by overriding layout params within LayoutManager:

    layoutManager = object : GridLayoutManager(context, 3, GridLayoutManager.HORIZONTAL, false){
        override fun checkLayoutParams(lp: RecyclerView.LayoutParams) : Boolean {
            // force width of viewHolder to be a fraction of RecyclerViews
            // this will override layout_width from xml
            lp.width = width / spanCount
            return true
        }
    }