Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How to achieve setOnClickListener in Kotlin?

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

Forth:

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

Here is an example on how to use the onClickListener in Kotlin

button1.setOnClickListener(object : View.OnClickListener{
            override fun onClick(v: View?) {
                //Your code here
            }})

Method 1:

txtNext.setOnClickListener {
        //Code statements
    }

Method 2:

class FirstActivity : AppCompatActivity(), View.OnClickListener {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_first)
    txtNext.setOnClickListener(this)
}

override fun onClick(v: View) {
    when (v.id) {
        R.id.txtNext -> {
            //Code statements
        }
        else -> {
            // else condition
        }
    }
  }
}