android 一次设置多个按钮的OnClickListener
android setOnClickListener multiple buttons at once
我有三个 ID 为 b00、b01、b02 的按钮,我希望它们在长按时都执行相同的操作。有没有比
更好的方法
b00.setOnLongClickListener {
//code
true
}
b01.setOnLongClickListener {
//same code
true
}
b02.setOnLongClickListener {
//same code
true
}
你可以这样做:
/...
b00.setOnLongClickListener(this)
b01.setOnLongClickListener(this)
b02.setOnLongClickListener(this)
}
//...
override fun onLongClick(v: View?): Boolean {
var id = v?.id
if ((id == b00.id) or (id == b01.id) or (id == b02.id)) {
//your code
return true
}
return false
}
根据您的示例,我假设您使用的是 Kotlin。
编程尽量简单易懂,不要重复。
由于 OnLongClickListener
您需要 return Boolean
您消耗的事件,我建议添加 inline 功能
inline fun consumeEvent(function: () -> Unit): Boolean {
function()
return true
}
然后,将通用代码从侦听器移动到新函数,例如 fun myFunction()
并调用它。
fun myFunction() {
// some code
}
b00.setOnLongClickListener { consumeEvent { myFunction() } }
b01.setOnLongClickListener { consumeEvent { myFunction() } }
b02.setOnLongClickListener { consumeEvent { myFunction() } }
我有三个 ID 为 b00、b01、b02 的按钮,我希望它们在长按时都执行相同的操作。有没有比
更好的方法b00.setOnLongClickListener {
//code
true
}
b01.setOnLongClickListener {
//same code
true
}
b02.setOnLongClickListener {
//same code
true
}
你可以这样做:
/...
b00.setOnLongClickListener(this)
b01.setOnLongClickListener(this)
b02.setOnLongClickListener(this)
}
//...
override fun onLongClick(v: View?): Boolean {
var id = v?.id
if ((id == b00.id) or (id == b01.id) or (id == b02.id)) {
//your code
return true
}
return false
}
根据您的示例,我假设您使用的是 Kotlin。
编程尽量简单易懂,不要重复。
由于 OnLongClickListener
您需要 return Boolean
您消耗的事件,我建议添加 inline 功能
inline fun consumeEvent(function: () -> Unit): Boolean {
function()
return true
}
然后,将通用代码从侦听器移动到新函数,例如 fun myFunction()
并调用它。
fun myFunction() {
// some code
}
b00.setOnLongClickListener { consumeEvent { myFunction() } }
b01.setOnLongClickListener { consumeEvent { myFunction() } }
b02.setOnLongClickListener { consumeEvent { myFunction() } }