Multiple click listeners on buttons

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

Yes, in Kotlin you can do it like this:

view.setOnClickListener(object : View.OnClickListener {
    override fun onClick(v: View?) {
        when(v?.id) {
            R.id.imgBack -> {/* do your code */}
            R.id.twoButton -> {/* do your code */}
            R.id.threeButton -> {/* do your code */}
            else -> {/* do your code */}
        }
    }
}

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.