有五种使用SetOnClickListener的方法:
第一:
button.setOnClickListener {
// Do some work here
}
第二:
button.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View?) {
// Do some work here
}
})
第三:
button.setOnClickListener(View.OnClickListener { view ->
// Do some work here
})
向前:
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
}
}
}
}
第五:
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
}
}
}
}
干杯!