第一行Kotlin系列(一)kotlin按钮点击事件
按钮findViewBuId
<Button android:id="@+id/mButton4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="跳转" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/mButton3" />
XML 没有变化
val button4 = findViewById
点击事件有三种写法
1.匿名内部类
button4.setOnClickListener {
Toast.makeText(this, "java", Toast.LENGTH_LONG).show()
}
这里就使用Toast打印一句话,Toast的写法和java中的写法一样
2.Activity实现全局OnClickListener接口
class MainActivity : AppCompatActivity(), View.OnClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initView()
}
在 AppCompatActivity类后加上 View.OnClickListener 用“,”分割,这种方法与java的区别是没有implements关键字表示实现接口。
private fun initView() {
val button1 = findViewById
override fun onClick(v: View?) {
when (v?.id) {
R.id.mButton1 ->
Toast.makeText(this, "java", Toast.LENGTH_LONG).show()
R.id.mButton2 ->
Toast.makeText(this, "java", Toast.LENGTH_LONG).show()
}
}
在kotlin中使用when替代了java中的switch,“:”符号改为了“->”。
3.指定onClick属性
fun mButton3(view: View) {
if (view.id == R.id.mButton3) {
finish()
}
}
代码中就实现了关闭当前Activity
以上