微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 Kotlin 覆盖 ListAdapter 的 onCurrentListChanged?

如何解决如何使用 Kotlin 覆盖 ListAdapter 的 onCurrentListChanged?

我希望覆盖 listadapteronCurrentListChanged,但代码 A 不起作用,我该如何解决

代码 A

myAdapter.onCurrentListChanged(){prevIoUsList,currentList ->
            
}

添加内容

致阿列克谢·罗曼诺夫:谢谢!

代码 C 可以正常工作,但是您回答的代码 D 无法工作,有什么错误

代码 C

private val myAdapter by lazy{
             VoiceAdapters(mHomeviewmodel,mPlay)
           }

代码 D

  private val myAdapter by lazy{
            VoiceAdapters(mHomeviewmodel,mPlay) {
               override fun onCurrentListChanged(prevIoUsList: MutableList<MVoice>,currentList: MutableList<MVoice>) {
                
               }
        }

两者

class VoiceAdapters (private val aHomeviewmodel: Homeviewmodel,private val mPlay: PlayInterface):
        listadapter<MVoice,VoiceAdapters.VoiceViewHolder>(MVoiceDiffCallback()) {

   ...
}

解决方法

您显示的代码看起来更像是试图调用 onCurrentListChanged,但是

  1. 那就是简单的 myAdapter.onCurrentListChanged(someList1,someList2);

  2. 可能不应该被手动调用。

覆盖 ListAdapter 的方法,您需要在定义 myAdapter(或它是其实例的任何类)时执行此操作。例如

val myAdapter = object : ListAdapter<SomeType> {
    override fun onCurrentListChanged(previousList: MutableList<SomeType>,currentList: MutableList<SomeType>) {
        ...
    }

    // other overrides
}

有关 object : ... 语法的说明和详细信息,请参阅 object expressions

当您已经拥有 myAdapter 时,为时已晚,尽管您可以创建一个新的 ListAdapter,它具有自己的 onCurrentListChanged 并委托 myAdapter 以用于其他方法。 Kotlin 特别支持这种接口模式,但 ListAdapter 是一个类,您必须手动完成所有操作:

val myAdapter2 = object : ListAdapter<SomeType> {
    override fun onCurrentListChanged(previousList: MutableList<SomeType>,currentList: MutableList<SomeType>) {
        ...
    }

    override fun getCurrentList() = myAdapter.getCurrentList()

    override fun getItemCount() = myAdapter.getItemCount()

    // etc.
}

代码 C 可以正常工作,但是您回答的代码 D 无法工作,有什么错误?

应该是

private val myAdapter by lazy {
    object : VoiceAdapters(mHomeViewModel,mPlay) {
        override fun onCurrentListChanged(previousList: MutableList<MVoice>,currentList: MutableList<MVoice>) {
            
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。