In this example, we will display a toast message by clicking on a Button. See the following example:
Step.1
MainActivity.kt
Add the following code in the MainActivity.kt class.
package com.study.kotlinkatta
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
class MainActivity : AppCompatActivity() {
lateinit var btn_clcik_to_toast: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn_clcik_to_toast =findViewById(R.id.btn_clcik_to_toast)
btn_clcik_to_toast.setOnClickListener {
Toast.makeText(applicationContext,"This is a Toast.",Toast.LENGTH_SHORT).show()
}
}
}
Step.2
activity_main.xml
Add the following code in the activity_main.xml file.
<?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">
<Button
android:id="@+id/btn_clcik_to_toast"
android:background="@color/colorAccent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp"
android:text="Click To Toast"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Output:
Comments
Post a Comment