Android - How to achieve setOnClickListener in Kotlin?

I wanted to know that how we set basic onClickListener in Kotlin for Android Development.


There are five ways to use SetOnClickListener:

First:

button.setOnClickListener {
    // Do some work here
}

Second:

button.setOnClickListener(object : View.OnClickListener {
    override fun onClick(view: View?) {
        // Do some work here
    }

})

Third:

button.setOnClickListener(View.OnClickListener { view ->
    // Do some work here
})

Fourth:

class MainActivity : AppCompatActivity(), View.OnClickListener{
   
    lateinit var button : Button
            
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button = findViewById(R.id.button1)
        button.setOnClickListener(this)
    }
        
    override fun onClick(view: View?) {
        when(view?.id){
            R.id.button1->{
                // do some work here
            }
        }
    }
}

Fifth:

class MainActivity : AppCompatActivity(){

    lateinit var button : Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button = findViewById(R.id.button1)
        button.setOnClickListener(listener)
    }
    
    val listener= View.OnClickListener { view ->
        when (view.getId()) {
            R.id.button1 -> {
                // Do some work here
            }
        }
    }
}

Cheers!


Suppose you have textView to click

text_view.text = "Hello Kotlin";

text_view.setOnClickListener {
    val intent = Intent(this@MainActivity, SecondActivity::class.java)
    intent.putExtra("key", "Kotlin")
    startActivity(intent)
}

Use below code

val textview = findViewById<TextView>(R.id.textview)
textview.setOnClickListener(clickListener)

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

clickListener code.

val clickListener = View.OnClickListener {view ->

    when (view.getId()) {
        R.id.textview -> firstFun()
        R.id.button -> secondFun()
    }
}