无法从Kotlin中的自定义ResyclerView扩展适配器

时间:2019-11-14 08:21:17

标签: java android kotlin android-recyclerview abstract-class

我正在尝试基于此post实现一个空状态回收器视图。我已经将解决​​方案迁移到Kotlin,但是问题是我无法从Kotlin中新定义的自定义回收器视图扩展 CustomRecyclerView.Adapter (Adapter是RecyclerView中定义的抽象类)。而且我观察到可以在Java中扩展相同的 CustomRecyclerView.Adapter

Customer RecyclerView实施

open class CustomRecyclerView: RecyclerView {


private var emptyStateView : View? = null

constructor(context: Context) : super(context)
constructor(context: Context , attrs: AttributeSet) : super(context,attrs)
constructor(context: Context , attrs: AttributeSet, defstyle: Int) : super(context,attrs,defstyle)


var observer: AdapterDataObserver = object : AdapterDataObserver() {

    override fun onChanged() {
        super.onChanged()
        initEmptyView()
    }

    override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
        super.onItemRangeRemoved(positionStart, itemCount)
        initEmptyView()
    }

    override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
        super.onItemRangeInserted(positionStart, itemCount)
        initEmptyView()
    }
}

private fun initEmptyView() {
    emptyStateView?.let {
        it.visibility = if (adapter == null || adapter!!.itemCount == 0) View.VISIBLE else View.GONE
        this@CustomRecyclerView.visibility = if (adapter == null || adapter!!.itemCount == 0) View.GONE else View.VISIBLE
    }
}

override fun setAdapter(adapter: Adapter<*>?) {
    val oldAdapter = getAdapter()
    super.setAdapter(adapter)
    oldAdapter?.unregisterAdapterDataObserver(observer)
    adapter?.registerAdapterDataObserver(observer)
}

/**
 * @param emptyView is the view which is going to display when the recycler view is empty
 * **/
fun setEmptyView(emptyView: View) {
    this.emptyStateView = emptyView
    initEmptyView()
}}

为Java和kotin中的扩展实现添加图像

Kotlin java

2 个答案:

答案 0 :(得分:0)

要总结评论:继承自RecyclerView.Adapter,请参见下文

YourAdapter: RecyclerView.Adapter<YourViewHolder>()

这只是一个提示,这是Kotlin扩展具有多个构造函数的类的方法:

class CustomRecyclerView @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0
) : RecyclerView(context, attrs, defStyleAttr)

有关更多信息,请检查@JvmOverloads

答案 1 :(得分:0)

它应该是RecyclerView.Adapter ..并将适配器设置为customRecyclerView。