1.监听函数
函数式
findViewById(R.id.btn_hello)?.setOnClickListener{
Toast.makeText(this,"Hello Kotlin",Toast.LENGTH_LONG).show()
}
函数作为变量
val mListener = fun (v:View?){
when(v?.id){
R.id.btn_hello -> Toast.makeText(this,"Hello Kotlin",Toast.LENGTH_LONG).show()
}
}
findViewById(R.id.btn_hello)?.setOnClickListener(mListener)
内部类实现View.OnClickListener接口
inner class MyListener:View.OnClickListener{
override fun onClick(v: View?) {
when(v?.id){
//this@MyListener MyListener's this
//this@MainActivity MainActivity's this
R.id.btn_hello -> Toast.makeText(this@MainActivity,"Hello Kotlin",Toast.LENGTH_LONG).show()
}
}
}
findViewById(R.id.btn_hello)?.setOnClickListener(MyListener())