Сбой при динамическом изменении LayoutManager на FlexboxLayoutManager - PullRequest
0 голосов
/ 25 июня 2019

Я должен использовать оба значения LinearLayoutManager или FlexbotLayoutManager, в зависимости от размера ребенка в RecyclerView.

Когда я изменяю LinearLayoutManager на FlexbotLayoutManager динамически, как:

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

Я сталкиваюсь с этой ошибкой:

java.lang.ClassCastException: android.support.v7.widget.RecyclerView $ LayoutParams нельзя привести к com.google.android.flexbox.FlexItem на com.google.android.flexbox.FlexboxHelper.calculateFlexLines (FlexboxHelper.java:439) на com.google.android.flexbox.FlexboxHelper.calculateHor HorizontalFlexLines (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) atroid.view.View.measure (View.java:22071)

Как это можно исправить?

1 Ответ

0 голосов
/ 25 июня 2019

Проблема в том, что 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)
    }
}
...