近期迹缀,Google宣布Kotlin成為了Android一級開發(fā)語言粹排。于是就剛剛簡單的研究了一下种远,查資料的時候發(fā)現(xiàn)現(xiàn)成的資料還是很少的,于是決定自己記錄一下顽耳,方便以后查看院促,也供其他人一個參考。
在android中斧抱,點(diǎn)擊事件大致分為三種寫法:
1. 匿名內(nèi)部類。
2. Activity實(shí)現(xiàn)全局OnClickListener接口渐溶。
3. 指定xml的onClick屬性咙崎。
今天用Kotlin實(shí)現(xiàn)這三種方式實(shí)現(xiàn)點(diǎn)擊事件
-
匿名內(nèi)部類:這種方式最簡單
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bt_click.setOnClickListener {
Toast.makeText(this,"點(diǎn)擊了",Toast.LENGTH_SHORT).show();
}
}
這里不需要new OnClicklistener惫皱。
-
全局實(shí)現(xiàn)OnClickListener接口:
class MainActivity : AppCompatActivity(), View.OnClickListener {
override fun onClick(v: View?) {
when (v?.id) {
R.id.bt_click ->
Toast.makeText(this, "點(diǎn)擊了", Toast.LENGTH_SHORT).show()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bt_click.setOnClickListener(this)
}
}
這種方法與java的區(qū)別是沒有implements關(guān)鍵字表示實(shí)現(xiàn)接口。
when就相當(dāng)于java中的switch。
“:”符號改為了“->”软吐。
-
指定onClick屬性:
fun click(v: View?) {
when (v?.id) {
R.id.bt_click ->
Toast.makeText(this, "點(diǎn)擊了", Toast.LENGTH_SHORT).show()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
<Button
android:id="@+id/bt_click"
android:layout_width="match_parent"
android:layout_height="50dp"
android:onClick="click"
android:text="點(diǎn)擊" />