首页 > 解决方案 > 将 LayoutManager 动态更改为 FlexboxLayoutManager 时崩溃

问题描述

我必须同时使用LinearLayoutManagerFlexbotLayoutManager取决于 RecyclerView 中的孩子大小。

当我更改LinearLayoutManagerFlexbotLayoutManager动态喜欢时:

recyclerView.layoutManager = 
            FlexibleFlexboxLayoutManager(context).apply {
                    flexWrap = FlexWrap.NOWRAP
                    flexDirection = FlexDirection.ROW
            }

我面临这个错误:

java.lang.ClassCastException:android.support.v7.widget.RecyclerView$LayoutParams 无法在 com.google.android.flexbox.FlexboxHelper.calculateFlexLines(FlexboxHelper.java:439) 处转换​​为 com.google.android.flexbox.FlexItem com.google.android.flexbox.FlexboxHelper.calculateHorizo​​ntalFlexLines(FlexboxHelper.java:243) 在 com.google.android.flexbox.FlexboxLayoutManager.updateFlexLines(FlexboxLayoutManager.java:955) 在 com.google.android.flexbox.FlexboxLayoutManager.onLayoutChildren( FlexboxLayoutManager.java:731) 在 android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3924) 在 android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3336) 在 android.view.View .measure(View.java:22071)

如何修复?

标签: androidandroid-flexboxlayout

解决方案


问题是FlexboxLayoutManager只覆盖generateLayoutParams(Context c, AttributeSet attrs)但不覆盖generateLayoutParams(ViewGroup.LayoutParams lp)

所以解决方案是实现该方法:

class SafeFlexboxLayoutManager : FlexboxLayoutManager {

    constructor(context: Context) : super(context)

    constructor(context: Context, flexDirection: Int) : super(context, flexDirection)

    constructor(context: Context, flexDirection: Int, flexWrap: Int) : super(context, flexDirection, flexWrap)

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(
        context,
        attrs,
        defStyleAttr,
        defStyleRes
    )

    override fun generateLayoutParams(lp: ViewGroup.LayoutParams): RecyclerView.LayoutParams {
        return FlexboxLayoutManager.LayoutParams(lp)
    }
}

推荐阅读