问题描述
在过去的一天中,我没有发现任何内容可以显示如何执行此操作,我所看到的一切都与一个基本按钮有关,我无法复制该按钮以用于图像按钮。尽管我发现使用setonClickListener的唯一情况是5岁以上,但似乎根本无法使用。
是否有一个Storyboard相当于Android Studio中的链接活动?
这是我发现但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)
}
})
}
}
,
问题是您没有在onClick
覆盖中包含View参数。 OnClickListener.onClick
的签名包含一个View
(被单击的视图)作为其参数,因此onClick()
(无参数)与该签名不匹配。
您可以显式添加它(在这种情况下,您还需要用this
显式引用活动的ActivityName.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)
}