Multiple click listeners on buttons

Viewed 15950

I want to know how to add multiple click events to buttons defined in XML, as previously, in Java, we implemented View.onClickListener interface and did the rest of the work in onClick method.
Example:

@Override
public void onClick(View v) {

switch (v.getId()) {

    case R.id.oneButton:
        // do your code
        break;

    case R.id.twoButton:
        // do your code
        break;

    case R.id.threeButton:
        // do your code
        break;

    default:
        break;
    }

}

I'm making a basic calculator app with the new Kotlin but it seems Kotlin has no such provisions, instead my code looks too long and verbose, as I'm attaching events to all buttons individually.
Can someone tell me how to do the same way in Kotlin? Thanks

7 Answers

For multiple onClickListeners in kotlin (version:1.1.60), the following helped me. Hope it'll be useful to someone else too.

Implement OnClickListener to activity like:

class YourActivity : AppCompatActivity(), View.OnClickListener

set your button in onCreate():

val button = findViewById<Button>(R.id.buttonId)

and assign onclick to the button in onCreate():

button.setOnClickListener { onClick(button) }

and in the override method of onClick() :

 override fun onClick(v: View) {
    when (v.id) {
        R.id.buttonId -> { //your code  }
        ..
        ..
        ..
        else -> { //your code  }
   }
 }

you can create anonymous object from an inteface View.ClickListener and pass it to setOnClickListener function

private val clickListener = View.OnClickListener { p0 ->
    when (p0.id) {
        ....
    }
}

... setOnClickListener(clickListener)
Related