Multiple click listeners on buttons

Anand Rajput :

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

Rahul :

First of all implement OnClickListener in your Activity, like

class MainActivity : Activity , OnClickListener

then override its implementation like

func onClick(v:View) {  
   //use when here like
   case R.id.youview -> {
   // do your work on click of view
    }

Don't forgot to set clicklistener on your View.

  yourView.setOnClickListener(this)

Or for better understanding go step by step -

  1. Implement OnClickListener in your Activity.

  2. Compiler will ask you to implement overrided methods. Implement those.

  3. Copy paste your java code which you wrote inside onClick method, that can be converted by kotlin itself or write down when conditions.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=463244&siteId=1