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

Vit*_*lii 0 android gridlayoutmanager

我有一个包含RecyclerView. 回收器中的每个项目都是一个简单的复选框。我需要把它画成三列。

为此,我使用 GridLayoutManager

layoutManager = GridLayoutManager(context, 3, GridLayoutManager.HORIZONTAL, false)
Run Code Online (Sandbox Code Playgroud)

我在结果中看到的是这个

在此处输入图片说明

不错。问题是我需要将每列的宽度设置为对话框宽度的 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>
Run Code Online (Sandbox Code Playgroud)

我的回收器创建的宽度等于父级

 <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
Run Code Online (Sandbox Code Playgroud)

任何想法如何以百分比设置宽度?

Paw*_*wel 8

如果您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
    }
}
Run Code Online (Sandbox Code Playgroud)