我可以在GridLayoutManager中以百分比设置列的宽度吗?

时间:2019-03-27 17:52:46

标签: android gridlayoutmanager

我有一个包含RecyclerView的警报对话框。回收站中的每个项目都是一个简单的复选框。我需要将其绘制成三列。

为此,我使用GridLayoutManager

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

我看到的结果是这个

enter image description here

不错。问题是我需要将每列的宽度设置为对话框宽度的33%。我的复选框没有固定的像素宽度,因为文本可能会有所不同。这是用于回收站的布局。

<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>

我的回收站的宽度等于父级宽度

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

有什么想法如何以百分比设置宽度?

1 个答案:

答案 0 :(得分:2)

如果RecyclerView的布局正确,则可以通过覆盖ViewHolder中的布局参数来强制设置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
    }
}
相关问题