Kotlin中的多重继承

时间:2015-03-13 16:39:21

标签: multiple-inheritance kotlin

考虑以下示例

public class SomeActivity() : Activity(), OnClickListener {

    override fun onCreate(Bundle?: savedInstanceState) {
        super<Activity>.onCreate(savedInstanceState)

        ...

        someButton.setOnClickListener(this) // How do I refer to the `OnClickListener` implementation?
    }
}

如何在上述代码段中引用OnClickListener实现?

2 个答案:

答案 0 :(得分:1)

不要忘记实施onClick(View)功能并更改onCreate签名。之后代码如下所示:

public class SomeActivity() : Activity(), OnClickListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super<Activity>.onCreate(savedInstanceState)

        val someButton = Button(this)

        someButton.setOnClickListener(this)
    }

    override fun onClick(v: View) {
        // TODO implement
    }
}

答案 1 :(得分:0)

Not wanting to create an Android project, I created a mock up of your classes and there are no errors using the code mentioned in another answer:

// mocked up classes

interface Bundle {}

open class Activity {
    open fun onCreate(savedInstanceState: Bundle?) {}
}
interface View {}

interface OnClickListener {
    fun onClick(v: View)
}

open class Button(a: Activity) {
    fun setOnClickListener(o: OnClickListener) {}
}

// the usage, showing no error:

public class SomeActivity() : Activity(), OnClickListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super<Activity>.onCreate(savedInstanceState)

        val someButton = Button(this)

        someButton.setOnClickListener(this) // NO ERROR
    }

    override fun onClick(v: View) {
        // TODO implement
    }
}