问题描述
我希望覆盖 listadapter 的 onCurrentListChanged
,但代码 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
,但是
-
那就是简单的
myAdapter.onCurrentListChanged(someList1,someList2)
; -
它可能不应该被手动调用。
要覆盖 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>) {
}
}
}