SetOnClickListener를 사용하는 방법에는 5 가지가 있습니다.
먼저:
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
}
}
}
}
건배!