android - 自定义 RecyclerView 为空
问题描述
我正在尝试扩展RecyclerView
,但应用程序崩溃,因为自定义回收器视图为空。
MyRecyclerView.kt
class MyRecyclerView @JvmOverloads constructor
(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0)
: RecyclerView(context), RecyclerView.OnItemTouchListener {
override fun onTouchEvent(p0: RecyclerView, p1: MotionEvent) {
// no op
}
override fun onInterceptTouchEvent(rv: RecyclerView, event: MotionEvent): Boolean {
return false
}
override fun onRequestDisallowInterceptTouchEvent(p0: Boolean) {
// no op
}
}
布局.xml
<com.myapp.view.MyRecyclerView
android:id="@+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:itemCount="1"
tools:listitem="@layout/row_item"
tools:orientation="horizontal" />
这是它在onViewCreated()
片段中崩溃的地方:
binding.root.myRecyclerView.adapter = adapter
binding.root.myRecyclerView.layoutManager =
LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
出现此错误:
java.lang.IllegalStateException: binding.root.myRecyclerView 不能为空
不知道为什么这RecyclerView
是空的。谢谢。
解决方案
用XML 属性定义的AView
的 ID在传递给两个参数构造函数中。如果你没有在超级构造函数调用中传递它,ID 将不会在类中自动设置,并且你的自定义将不会在.android:id
AttributeSet
View
View
findViewById()
在这种情况下,我们只需要将其余参数添加到 super 调用中:
RecyclerView(context, attrs, defStyle)
您可能还想设置适当的defStyle
默认值,即R.attr.recyclerViewStyle
,至少在最新的库版本中。
推荐阅读
- excel - 提取最小值的名称excel
- c# - 视图更改后绑定的 ComboBoxItem 变量变为空
- javascript - 为什么我的 jQuery 可以内联工作,但不能在外部工作?
- swift - 如何选择 algolia 搜索命中并将其重定向到所需的 Viewcontroller?
- sql - 如何在 DolphinDB 查询中从分布式表中消除重复记录
- javascript - 在某些站点上,MouseEvent 对象的 x 和 y 值与 Debugger API 调度的 x 和 y 值不同
- java - 有没有办法让 System.out.print 在循环中打印一次不同的东西?
- c++ - 有没有办法用父类命名空间/类空间来引用子类?
- node.js - Firestore 函数 listCollections() 仅返回空数组
- javascript - 如何删除 Quill.js 工具栏边框?