第一行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<Button>(R.id.mButton4)

点击事件有三种写法

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<Button>(R.id.mButton1)
        val button2 = findViewById<Button>(R.id.mButton2)
        val button4 = findViewById<Button>(R.id.mButton4)
        val button5 = findViewById<Button>(R.id.mButton5)
        val button6 = findViewById<Button>(R.id.mButton6)
        val button7 = findViewById<Button>(R.id.mButton7)
 
        button1.setOnClickListener(this)
        button2.setOnClickListener(this)
        button7.setOnClickListener(this)
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属性

    <Button
        android:id="@+id/mButton3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="mButton3"
        android:text="关闭"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/mButton2" />
    fun mButton3(view: View) {
        if (view.id == R.id.mButton3) {
            finish()
        }
    }

代码中就实现了关闭当前Activity

以上

原文地址:https://www.cnblogs.com/MyXcc/p/12881053.html