Display Toast in Android

Display Toast in Android

A toast is a small popup message that appears on the screen. A toast can inform about running processes and automatically disappears after a few seconds. The size of toast depends on the space required for the message. A toast is not clickable.

A layout XML file contains a Button that displays a toast when it was pressed.

app/src/main/res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/myButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Open" /> </RelativeLayout>

A toast can be created using the method Toast.makeText(). The last parameter is duration, which defines how long to display a toast.

ValueDescription
LENGTH_SHORTA toast will be shown for 2000 milliseconds.
LENGTH_LONGA toast will be shown for 3500 milliseconds.

We can display the toast by using show() method.

app/src/main/java/com/example/app/MainActivity.kt

package com.example.app import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) myButton.setOnClickListener { showToast() } } private fun showToast() { val toast = Toast.makeText(this, "Hello world", Toast.LENGTH_LONG) toast.show() } }

Leave a Comment

Cancel reply

Your email address will not be published.