如何将onclick函数(或onclicklistner)设置为多个按钮?原因是,我不想为每个按钮编写相同的代码,其中唯一不同的变量是每个按钮的“感觉”。
这是我的代码:(对不起,如果没有意义,我现在正在尝试中!)
class Users(val Feeling: String, val Location: String) {
constructor() : this("","") {
}
}
从“类”文件中:
/app
答案 0 :(得分:1)
点击侦听器会收到一个view
作为参数,您可以使用它来通过其ID来识别按钮
val clickListener = View.OnClickListener { button ->
val feeling = when (button.id) {
R.id.button_1 -> /* get feeling */
R.id.button_2 -> /* ... */
...
else -> return
// use the feeling to do whatever you need
}
然后,您可以将此点击侦听器设置为所有按钮。
编辑:
要设置点击监听器,您有不同的选择。您可以将findViewById
用于每个binding
对象,然后使用override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
view.findViewById<Button>(R.id.button_1).setOnClickListener(clickListener)
view.findViewById<Button>(R.id.button_2).setOnClickListener(clickListener)
}
对象绑定绑定点击监听器,具体取决于您的设置。
例如
json.load(f)