首页 > 解决方案 > 自定义 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是空的。谢谢。

标签: androidandroid-recyclerview

解决方案


用XML 属性定义的AView的 ID在传递给两个参数构造函数中。如果你没有在超级构造函数调用中传递它,ID 将不会在类中自动设置,并且你的自定义将不会在.android:idAttributeSetViewViewfindViewById()

在这种情况下,我们只需要将其余参数添加到 super 调用中:

RecyclerView(context, attrs, defStyle)

您可能还想设置适当的defStyle默认值,即R.attr.recyclerViewStyle,至少在最新的库版本中。


推荐阅读