VOOZH about

URL: https://www.geeksforgeeks.org/android/toasts-android-studio/

⇱ Toasts for Android Studio - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Toasts for Android Studio

Last Updated : 31 Jan, 2025

A toast provides a simple popup message that is displayed on the current activity UI screen (e.g. Main Activity). 

Example:

👁 Image

Syntax:

// To get Context
Context context = getApplicationContext();

// Message to display
String text = "Toast message";

// Toast time duration, can also set manual value
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);

// To show the toast
toast.show();

We can also create toast with single line by passing variables directly to makeText() function. This method takes three parameters context, popup text message, the toast duration. After creating Toast object you can display the toast by using show() method.

Example :

Toast.makeText(MainActivity.this, "Error"+ msg, Toast.LENGTH_SHORT).show();

Creating a Custom Toast

If you are not satisfied with simple Toast view in Android, then you can go ahead to make a custom Toast. Actually, custom Toast is a modified simple Toast that makes your UI more attractive. So that when you create a custom Toast then two things are required, one is XML(custom_toast.xml) required for layout view of custom Toast and another is activity class (custom_activity.java) file where you can write Java code. Java class file passes the root View object to the setView(View) method.  

activity_main.xml: (Creating custom Toast in main activity file)


This is a XML layout for example purposes, so if you want your own design then you can create your own XML.

MainActitvity.java:

Output of the above Application:

Toast appears and disappears.


Click Here to Learn to Create Android Application

Comment
Article Tags:
Article Tags:

Explore