Search code examples
javaclasskotlinmethodsonclicklistener

onClick function for multiple buttons


How would I set an onclick function (or onclicklistner) to multiple buttons? The reason being, is I don't want to have to write this same code for each button, where the only different variable would be "Feeling" for each button.

This is my code: (Sorry if it doesn't make sense, I'm just experimenting right now!)

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)
        }
    }

From the Class file:

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

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

    }
}

Solution

  • The click listener receives a view as parameter, you can use that to identify the button by it's 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
    }
    

    You would then set this click listener to all your buttons.

    Edit: to set the click listener, you have different options. You can use findViewById for each of them, using a binding object and then bind the click listener, it depends on your setup.

    For instance

    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)
    }