Android 自定义RecyclerView为空

Android 自定义RecyclerView为空,android,android-recyclerview,Android,Android Recyclerview,我正在尝试扩展RecyclerView,但由于自定义回收器视图为空,应用程序崩溃 MyRecyclerView.kt class MyRecyclerView @JvmOverloads constructor (context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : RecyclerView(context), RecyclerView.OnItemTouchListener { over

我正在尝试扩展
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
    }
}
layout.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" />
出现此错误时:

java.lang.IllegalStateException:binding.root.myRecyclerView不能 无效


不确定此
RecyclerView
为空的原因。谢谢。

使用
android:ID
XML属性定义的
视图的ID位于传递给两个+参数构造函数的
AttributeSet
中。如果在超级构造函数调用中未传递该ID,则不会在
视图
类中自动设置ID,并且在
findViewById()中找不到自定义的
视图

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

RecyclerView(context, attrs, defStyle)

您可能还希望至少在最新的库版本中设置相应的
defStyle
默认值,即
R.attr.recyclerViewStyle

必须将
属性集
传递给超级构造函数。否则,绝不会在
视图上设置ID。对于所有四个构造函数,您似乎只传递了
上下文
。这就解决了@MikeM。如果你把它作为答案贴出来,我会接受的。谢谢
RecyclerView(context, attrs, defStyle)