The Wayback Machine - https://web.archive.org/web/20250126175515/https://www.geeksforgeeks.org/android-toast-in-kotlin/
Open In App

Android Toast in Kotlin

Last Updated : 13 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A Toast is a short alert message shown on the Android screen for a short interval of time. Android Toast is a short popup notification which is used to display information when we perform any operation in our app. In this tutorial, we shall not just limit ourselves by creating a lame toast but also do some user-interactive stuff. First, we shall create a screen with an Edit Text (Text box to take input) and a Button.

Step By Step Implementation to Demonstrate

Step 1: Create a project in Android Studio with an empty activity and make sure that you have configured the app with Kotlin language.

Step 2: In the project window on the left side, navigate to app > res > layout > activity_main.xml.

Directory_struc

Here we are going to add an Edit Text and a button. So, remove the hello word Text View in the XML. Now your XML should look like this.

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">

    <EditText
        android:id="@+id/messageEditText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Message to toast"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toStartOf="@id/toastButton"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_margin="20sp"/>

    <Button
        android:id="@+id/toastButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Toast"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_margin="20sp"/>


</androidx.constraintlayout.widget.ConstraintLayout>


Step 3 : Let’s align the edit text and button. To make the components linked in Android we have constraints. We shall keep the Button at the end of Edit Text and Edit Text at the beginning of Button.

Add the following for Button.

app:layout_constraintStart_toEndOf="@+id/messageEditText"

Add the following for EditText.

app:layout_constraintEnd_toStartOf="@+id/toastButton"

Save the XML file and check the design tab (you can find it at the bottom left corner of editor tab). You can see the EditText and Button aligned on top of the application.


Step 4: Now, Let’s go to the Kotlin class file and make the toast happen. Open the Kotlin class file in app > java > com.example.toastdemo > MainActivity.kt

Add the following method to the class.

Kotlin
fun toastMessage(view: View)
{
    val messageEditText = findViewById<EditText>(R.id.messageEditText)
    val message = messageEditText.text.toString()
    var toast = Toast.makeText(this, message, Toast.LENGTH_LONG)
    toast.show()
}


Here, messageEditText is the object for EditText we have created in the Layout file in Step 3. To get the contents of EditText we have used the text property and stored it in a variable message. Making a Toast – here is the heart of this tutorial,

var toast = Toast.makeText(this, message, Toast.LENGTH_LONG)
Toast.makeText() creates a toast and returns it and we should pass three parameters:
  • context – The context to use. Usually your {@link android.app.Application}or {@link android.app.Activity} object.
  • text – The text to show. Can be formatted text.
  • duration – How long to display the message. Either {@link #LENGTH_SHORT} or {@link #LENGTH_LONG}

We are storing the Toast in a variable toast. To make the Toast visible we should call toast.show()


Step 5: Now we shall add an on click event listener to the button and make it to call our toastMessage() method when a click/tap was done to the button.

Go back to the activity_main.xml layout file and add this attribute to the Button

android : onClick = "toastMessage"

And that’s all we are done! Now run the App, enter a message in edit text and click the button. It will toast the message.

Hiding the Android Soft Keyboard after clicking the Toast button to see a clear Toast

Kotlin
fun hideKeyboard(activity: Activity)
{
    val view = activity.findViewById<View>(android.R.id.content) if (view != null)
    {
        val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE)
                as InputMethodManager
            imm.hideSoftInputFromWindow(view.windowToken, 0)
    }
}


Add the above method to the main activity class and call it before making toast.

The Whole MainActivity.kt Program is mentioned below:

MainActivity.kt
package com.gfg.tost_kotlin

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

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

        // Get reference to the button with the ID "toastButton"
        val mybutton: Button = findViewById(R.id.toastButton)
        
        // Set an OnClickListener for the button
        mybutton.setOnClickListener {
            // Call toastMessage function to display a toast
            toastMessage(it)
            // Call hideKeyboard function to hide the keyboard
            hideKeyboard(this)
        }

    }

    // Function to display atoast message
    fun toastMessage(view: View) {
        // Get reference to the EditText with the ID "messageEditText"
        val messageEditText = findViewById<EditText>(R.id.messageEditText)
        // Get the text from the EditText
        val message = messageEditText.text.toString()
        // Create a toast message with the text from the EditText
        val toast = Toast.makeText(this, message, Toast.LENGTH_LONG)
        // Show the toast message
        toast.show()
    }

    // Function to hide the keyboard
    fun hideKeyboard(activity: Activity) {
        // Get the root view of the activity
        val view = activity.findViewById<View>(android.R.id.content)
        if (view != null) {
            // Get the InputMethodManager service
            val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            // Hide the keyboard
            imm.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }
}

Run as Emulator:




Next Article

Similar Reads

three90RightbarBannerImg