多个按钮的onClick函数

onClick function for multiple buttons

如何为多个按钮设置一个 onclick 函数(或 onclicklistner)?原因是,我不想为每个按钮编写相同的代码,其中唯一不同的变量是每个按钮的“感觉”。

这是我的代码:(抱歉,如果没有意义,我现在只是在试验!)

fun onClick(view: View) {
        val database = FirebaseDatabase.getInstance()
        val myRef = database.getReference("Users")
        val userLocation = "New York"
        val userId = myRef.push().key
        val info = Users(Feeling = "Good", Location=userLocation)

        if (userId != null) {
            myRef.child(userId).setValue(info)
        }
    }

来自 Class 文件:

class Users(val Feeling: String, val Location: String) {

    constructor() : this("","") {

    }
}

点击侦听器接收一个 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)
}