Android - Kotlin - object must be declared abstract or implement abstract member

前端 未结 2 1061
[愿得一人]
[愿得一人] 2021-01-13 00:03

I have set an ItemClickLister for my RecyclerView like this:

ItemClickSupport.addTo(recyclerView!!).setOnItemClickListener(
                    object : Item         


        
相关标签:
2条回答
  • 2021-01-13 00:43

    Your interface and method signatures do not match. Your interface is declaring one function as:

    fun onItemClicked(recyclerView: RecyclerView, position: Int, v: View)
    

    And you override it as:

    fun onItemClicked(recyclerView: RecyclerView?, position: Int, v: View?)
    

    Those are not the same method signatures.

    If this was a Java interface, you can override while changing nullability because it isn't clear what the nullability is (given no annotations in the Java code). But since you ported it to a Kotlin interface you must override using the same exact signature. You instead made both RecyclerView? and View? nullable which results in a mismatch to the original signature. Change your overridden function to be:

    override fun onItemClicked(recyclerView: RecyclerView, position: Int, v: View)
    

    Since this is a Kotin interface, you cannot use the SAM conversion to a Lambda so that is why the other answer previously provided does not work. If this was a Java interface, you could do that. You can track SAM conversions for Kotlin interfaces in KT-7770.

    If you wanted this code to be more idiomatic Kotlin you would want function references or lambdas instead of interfaces, and you should just do that instead of relying on SAM conversion. You can read more about that in Higher-Order Functions and Lambdas. This is outside the scope of your question to go into more detail.

    0 讨论(0)
  • 2021-01-13 00:56

    Try with it:

    ItemClickSupport.addTo(listView).setOnItemClickListener(object : ItemClickSupport.OnItemClickListener{
            override fun onItemClicked(recyclerView: RecyclerView, position: Int, v: View) {
                val row = recyclerView!!.getChildAt(position)
                val el = row.findViewById(R.id.active_expandablelayout) as ExpandableLayout
    
                if (el.isExpanded) {
                    el.collapse()
                } else {
                    el.expand()
                }
            }
    
        })
    
    0 讨论(0)
提交回复
热议问题