Search code examples
androidonlongclicklistener

android setOnClickListener multiple buttons at once


I have three buttons with ids b00, b01, b02 that I want to all do the same thing when they are long clicked. Is there a better way to do this than

b00.setOnLongClickListener {
        //code
         true
}

b01.setOnLongClickListener {
         //same code
         true
}

b02.setOnLongClickListener {
        //same code
        true
}

Solution

  • You can do this:

        /...
    
        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
    }