【问题标题】:How can I override onCurrentListChanged of ListAdapter with Kotlin?如何使用 Kotlin 覆盖 ListAdapter 的 onCurrentListChanged?
【发布时间】:2021-03-30 06:07:15
【问题描述】:

我希望覆盖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()) {

   ...
}

【问题讨论】:

    标签: kotlin android-listadapter


    【解决方案1】:

    您显示的代码看起来更像是在尝试调用 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>) {
                
            }
        }
    }
    

    【讨论】:

    • 谢谢!请您看看我在问题中添加的内容吗?
    • 谢谢!在我将class VoiceAdapters 设置为open class VoiceAdapters 后,您的代码运行良好。
    • 代码 D 和你的代码一样,为什么代码 D 不起作用?
    • 这根本不是合法的 Kotlin 语法。您是否可能来自 Java 并期望像调用构造函数一样删除 new
    猜你喜欢
    • 2021-05-03
    • 2019-03-21
    • 1970-01-01
    • 2021-10-15
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多