android - 将 LayoutManager 动态更改为 FlexboxLayoutManager 时崩溃
问题描述
我必须同时使用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.FlexboxHelper.calculateFlexLines(FlexboxHelper.java:439) 处转换为 com.google.android.flexbox.FlexItem com.google.android.flexbox.FlexboxHelper.calculateHorizontalFlexLines(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)
如何修复?
解决方案
问题是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)
}
}
推荐阅读
- java - Activiti 的 RuntimeServiceImpl::startProcessInstanceByKey 在并发环境中无法正常工作
- mongodb - 根据另一个集合数据更新 mongo 字段
- php - PHP:如何在执行数组后从 HTML 输入标签中回显描述
- c++ - “新”创建实例的所有成员变量是否都存在于堆上而不是堆栈上?
- python - 通过字典中的 HTML 进行解析
- c++ - 在我的 c++ 应用程序中可以使用多少个线程
- docker - 使用绑定挂载运行容器化 MongoDB
- ios - 无法成功准备 iOS
- javascript - OIDC 客户端在手动 jwksSigningKeys 上不断刷新
- pdf - Turnjs 在同一文件中使用 pdfjs 将 tcpdf 输出显示为翻书