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

Rea*_*God 7 android android-layout kotlin android-imagebutton

在过去的一天中,我没有找到任何显示如何执行此操作的内容,我所看到的所有内容都带有一个基本按钮,我无法复制该按钮以与图像按钮一起使用。使用 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)
            }
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

给出以下错误:

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

后监听器

Rya*_*ley 6

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

this您可以显式添加它(在这种情况下,您还需要使用显式引用 Activity ActivityName.thisthis否则引用 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)
        }
    })
Run Code Online (Sandbox Code Playgroud)

或者使用 Kotlin 的SAM 转换来隐式添加它(我会这样做):

    // 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)
    }
Run Code Online (Sandbox Code Playgroud)