First line kotlin series kotlin button click event

Button findViewBuId

    <Button
        android:id="@+id/mButton4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Jump"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/mButton3" />

XML doesn't change

val button4 = findViewById<Button>(R.id.mButton4)

There are three ways to write click events

1. Anonymous inner class

button4.setOnClickListener {
            Toast.makeText(this, "java", Toast.LENGTH_LONG).show()
        }

Here is a sentence printed with toast. Toast is written in the same way as java

2.Activity implements the global OnClickListener interface

class MainActivity : AppCompatActivity(), View.OnClickListener {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        initView()
    }

After AppCompatActivity class, add View.OnClickListener to be separated by ",". The difference between this method and java is that there is no implementation keyword to represent the implementation interface.

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()
        }
    }

In kotlin, when is used instead of switch in java, and the ':' sign is changed to '- >'.

3. Specify onClick property

    <Button
        android:id="@+id/mButton3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="mButton3"
        android:text="close"
        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()
        }
    }

Close the current Activity in the code

above

Tags: Android Java xml

Posted on Wed, 13 May 2020 11:50:23 -0400 by jakep