kotlin for android click event and start activity

created at 07-12-2021 views: 1

1. Kotlin click event

xml layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.boxunpark.www.kotlinapplication.MainActivity">

    <Button
        android:id="@+id/hello_text"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:text="Hello World!" />

    <Button
        android:id="@+id/click"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:text="click" />

</LinearLayout>

//The first way to click
hello_text.setOnClickListener {
    ...
}
//The second way to click
click.setOnClickListener({ view ->
    ...
})

2.Kotlin opens an Activity:

When implemented in java, we are like this:

startActivity(new Intent(this,SecondActivity.class));

Implementation using Kotlin

 startActivity(Intent(this@MainActivity, SecondActivity::class.java))

3. Assign value to TextView in Kotlin

3.1 Use java


TextView hello_text=(TextView)findViewById(R.id.hello_text)
hello_text.settext("Hello world")

3.2 Use Kotlin

 hello_text.text="Hello world"
created at:07-12-2021
edited at: 07-12-2021: