对象不是抽象的,没有实现抽象成员 public abstract fun onClick(p0: View!): Unit

Object is not abstract and does not implement abstract member public abstract fun onClick(p0: View!): Unit

在过去的一天里,我没有找到任何显示如何执行此操作的内容,我看到的所有内容都带有一个基本按钮,我无法复制它以用于图像按钮。使用 setOnClickListener 似乎根本不起作用,尽管我发现使用它们的唯一案例是 5 年以上。

在 Android Studio 中是否有等效于链接活动的 Storyboard?

这是我发现的一个 7 岁的例子。

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val myButton =
            findViewById<View>(R.id.live) as ImageButton

        myButton.setOnClickListener(object : OnClickListener() {
            // When the button is pressed/clicked, it will run the code below
            fun onClick() {
                // Intent is what you use to start another activity
                val intent = Intent(this, LiveActivity::class.java)
                startActivity(intent)
            }
        })
    }
}

出现以下错误:

Object is not abstract and does not implement abstract member public abstract fun onClick(p0: View!): Unit defined in android.view.View.OnClickListener

修复

更改自:

 myButton.setOnClickListener(object : OnClickListener { })

 myButton.setOnClickListener(object : View.OnClickListener { })

所以方法将是:

override fun onClick(v: View?) {
   // Do something
}

代替你的:

fun onClick() {

}

完整代码:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val myButton = findViewById<ImageButton>(R.id.live)

        myButton.setOnClickListener(object : View.OnClickListener {
            // When the button is pressed/clicked, it will run the code below
            override fun onClick(v: View?) {
                // Intent is what you use to start another activity
                val intent = Intent(this, LiveActivity::class.java)
                startActivity(intent)
            }
        })
    }
}

问题是您没有将 View 参数包含到 onClick 覆盖中。 OnClickListener.onClick 的签名包含一个 View(被点击的视图)作为其参数,因此 onClick()(没有参数)与该签名不匹配。

您可以显式添加它(在这种情况下,您还需要使用 ActivityName.this 显式引用 Activity 的 this,因为 this 指的是否则为 OnClickListener):

    myButton.setOnClickListener(object : View.OnClickListener {
        // When the button is pressed/clicked, it will run the code below
        override fun onClick(view: View) {
            // Replace ActivityName with the name of your Activity that this is in
            val intent = Intent(ActivityName.this, LiveActivity::class.java)
            startActivity(intent)
        }
    })

或使用 Kotlin 的 SAM conversions 隐式添加它(我会采用这种方法):

    // When the button is pressed/clicked, it will run the code below
    myButton.setOnClickListener { // there's an implicit view parameter as "it"
        // Intent is what you use to start another activity
        val intent = Intent(this, LiveActivity::class.java)
        startActivity(intent)
    }