Sunday, May 22, 2022

Simple example of Button and Toast (Android Kotlin)


activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    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"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_margin="10dp">

        <Button
            android:id="@+id/btn_A"
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Button A"
            android:layout_margin="5dp"/>
        <Button
            android:id="@+id/btn_B"
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Button B"
            android:layout_margin="5dp"/>
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt
package android_er.blogspot.com.myapp01

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast

private lateinit var btnA: Button
private lateinit var btnB: Button

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btnA = findViewById(R.id.btn_A)
        btnB = findViewById(R.id.btn_B)

        btnA.setOnClickListener(
            { view: View ->
                Toast.makeText(
                    this,
                    "Button A pressed",
                    Toast.LENGTH_LONG,
                ).show()
            },
        )

        btnB.setOnClickListener(
            { view: View ->
                Toast.makeText(
                    this,
                    "Button B pressed",
                    Toast.LENGTH_LONG,
                ).show()
            },
        )
    }
}

No comments:

Post a Comment