Android Java变道Kotlin(1)

2017-05-26  本文已影响0人  LeoooL

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())
上一篇 下一篇

猜你喜欢

热点阅读