Toasts in Android: A Complete Guide with Sample Code

In Android development, displaying short messages to users is a common requirement. Whether you want to notify users that data has been saved, show an error message, or confirm an action, Toast is one of the simplest ways to provide feedback.

A Toast is a small popup message that appears temporarily on the screen and disappears automatically after a short period. Unlike dialogs, Toasts do not require user interaction and do not interrupt the current activity.

This article explains what Toasts are, how to use them, customization options, best practices, and provides practical examples.


What is a Toast?

A Toast is a lightweight message displayed over the current screen. It appears for a short duration and then disappears automatically. Unlike dialogs or popups, a Toast does not require any user interaction and does not interrupt the current activity. Its primary purpose is to provide quick feedback to users without taking them away from their current task.

When a Toast is shown, it temporarily overlays the existing interface, typically near the bottom of the screen. After a few seconds, it fades away automatically. Because Toasts are transient and unobtrusive, they are well suited for displaying short informational messages.

For example, after saving a profile, an application might display:

Profile saved successfully

Similarly, when a user clicks a button, copies text to the clipboard, or completes a download, a Toast can provide immediate confirmation that the action has been performed.

One of the major advantages of Toasts is that they do not block the user interface. Users can continue scrolling, typing, or interacting with the application while the message is visible. This makes Toasts an effective way to communicate non-critical information without disrupting the user experience.

Typical use cases include:

  • Showing a successful operation message.
  • Informing users about network status.
  • Displaying validation errors.
  • Confirming button clicks.
  • Providing quick feedback without interrupting the user.

For example:

"Message sent"
"Profile updated successfully"
"No internet connection"

Basic Syntax

The simplest way to create a Toast is:

Toast.makeText(context, "Hello World!", Toast.LENGTH_SHORT).show()

Parameters:

  • context → Usually this or applicationContext
  • text → Message to display
  • durationToast.LENGTH_SHORT or Toast.LENGTH_LONG

Example 1: Show a Simple Toast

Kotlin

import android.os.Bundle
import android.widget.Button
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)

        val button = findViewById<Button>(R.id.btnToast)

        button.setOnClickListener {
            Toast.makeText(
                this,
                "Button clicked!",
                Toast.LENGTH_SHORT
            ).show()
        }
    }
}

XML

<Button
    android:id="@+id/btnToast"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Show Toast"/>

When the button is clicked, the message appears briefly and disappears automatically.


Toast Duration

When displaying a Toast message, Android allows developers to specify how long the message should remain visible. Since Toasts are intended for brief notifications, Android provides two predefined duration constants:

  • Toast.LENGTH_SHORT
  • Toast.LENGTH_LONG

These durations determine how long the Toast stays on the screen before disappearing automatically.

Toast.LENGTH_SHORT

Toast.LENGTH_SHORT displays the message for a short period, typically around 2 seconds. It is the most commonly used duration and is suitable for quick confirmations or status updates.

Short Duration

Toast.makeText(this, "Short message", Toast.LENGTH_SHORT).show()

The duration of Toast.LENGTH_SHORT is approximately 2 seconds, making it ideal for displaying brief confirmation or status messages. Since Toasts are designed to provide quick feedback without interrupting the user, short-duration messages should be concise and easy to read at a glance.

Long Duration

Toast.makeText(this, "Long message", Toast.LENGTH_LONG).show()

Duration is approximately 3.5 seconds.

Using applicationContext

The duration of Toast.LENGTH_LONG is approximately 3.5 seconds, which gives users more time to read messages that are slightly longer or more informative. It is useful when a short glance is not enough to understand the message, such as error descriptions or important status updates.

Toast.makeText(
    applicationContext,
    "Saved successfully",
    Toast.LENGTH_SHORT
).show()

This is useful when displaying Toasts from utility classes or services.During this time, the Toast remains visible on the screen without blocking user interaction. Users can continue scrolling, typing, or navigating through the app while the message is displayed.

LENGTH_LONG is typically used for messages such as:

  • Network or connectivity errors
  • Validation warnings
  • Important system notifications
  • Multi-word status messages
  • Retry or failure messages

Example 2: Toast After Saving Data

fun saveProfile() {

    // Save data

    Toast.makeText(
        this,
        "Profile saved successfully",
        Toast.LENGTH_LONG
    ).show()
}

Output:

Profile saved successfully

Showing Toast from a Fragment

Inside a Fragment, use:

Toast.makeText(
    requireContext(),
    "Fragment loaded",
    Toast.LENGTH_SHORT
).show()

Or:

Toast.makeText(
    activity,
    "Hello from Fragment",
    Toast.LENGTH_SHORT
).show()

Showing Toast from a RecyclerView Adapter

Pass the context to the adapter:

class UserAdapter(
    private val context: Context
) : RecyclerView.Adapter<UserAdapter.ViewHolder>() {

    fun onItemClicked() {
        Toast.makeText(
            context,
            "Item selected",
            Toast.LENGTH_SHORT
        ).show()
    }
}

Toast with String Resources

Instead of hardcoding text:

strings.xml

<string name="saved_successfully">
    Saved successfully
</string>

Kotlin

Toast.makeText(
    this,
    getString(R.string.saved_successfully),
    Toast.LENGTH_SHORT
).show()

This approach supports localization and cleaner code.


Showing Toast in Jetpack Compose

In Jetpack Compose, Toast is still used in the same way as in traditional Android Views, but you access the Context through Compose APIs instead of an Activity reference.

A Toast in Compose is typically used to show quick feedback to the user after an action like button click, form submission, or validation result.

Button(
    onClick = {
        Toast.makeText(
            context,
            "Compose Button Clicked",
            Toast.LENGTH_SHORT
        ).show()
    }
) {
    Text("Show Toast")
}
When the button is clicked, a Toast message appears for a short duration.

Complete example:

@Composable
fun MyScreen() {

    val context = LocalContext.current

    Button(
        onClick = {
            Toast.makeText(
                context,
                "Hello Compose",
                Toast.LENGTH_SHORT
            ).show()
        }
    ) {
        Text("Show Toast")
    }
}

Toast with Variables

val username = "John"

Toast.makeText(
    this,
    "Welcome $username",
    Toast.LENGTH_SHORT
).show()

Output:

Welcome John
Displaying Error Messages
if (email.isEmpty()) {

    Toast.makeText(
        this,
        "Email cannot be empty",
        Toast.LENGTH_SHORT
    ).show()
}

Showing Toast After Network Response

if (response.isSuccessful) {

    Toast.makeText(
        this,
        "Data loaded successfully",
        Toast.LENGTH_SHORT
    ).show()

} else {

    Toast.makeText(
        this,
        "Failed to load data",
        Toast.LENGTH_LONG
    ).show()
}

Avoid Showing Multiple Toasts

Rapid clicks may create many Toast messages:

button.setOnClickListener {

    Toast.makeText(
        this,
        "Clicked",
        Toast.LENGTH_SHORT
    ).show()
}

A better approach is to keep one Toast instance:

private var toast: Toast? = null

fun showToast(message: String) {

    toast?.cancel()

    toast = Toast.makeText(
        this,
        message,
        Toast.LENGTH_SHORT
    )

    toast?.show()
}

Usage:

showToast("Saved")

This prevents stacking multiple Toasts.

Using an Extension Function

Create a reusable extension:

fun Context.showToast(message: String) {
    Toast.makeText(
        this,
        message,
        Toast.LENGTH_SHORT
    ).show()
}

Usage:

showToast("Welcome")

Or:

applicationContext.showToast("Success")

Toast vs Snackbar

Both Toast and Snackbar are used to show short messages to users, but they are designed for different purposes and offer different levels of interaction and control.
Feature Toast Snackbar
Temporary message
User action button
Custom duration Limited Flexible
Material Design support Basic Better
Appears at bottom
Can be dismissed No Yes

Example Snackbar:

Snackbar.make(
    view,
    "Deleted successfully",
    Snackbar.LENGTH_LONG
).show()

For modern Material Design applications, Snackbar is often preferred.


Best Practices

Keep messages short

Good:

Profile updated

Bad:

The profile information has been successfully updated and synchronized with the server.

Avoid using Toast for critical information

Users may miss the message because it disappears automatically.

Use:

  • Dialogs
  • Snackbars
  • Notifications

for important events.

Use String Resources

Instead of:

Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show()

Prefer:

Toast.makeText(
    this,
    getString(R.string.success),
    Toast.LENGTH_SHORT
).show()

Prevent Toast Spamming

Cancel previous Toasts before displaying new ones.

Common Mistakes

Forgetting .show()

Incorrect:

Toast.makeText(
    this,
    "Hello",
    Toast.LENGTH_SHORT
)

Nothing appears.

Correct:

Toast.makeText(
    this,
    "Hello",
    Toast.LENGTH_SHORT
).show()

Using Wrong Context

Incorrect:

Toast.makeText(context, "Hello", Toast.LENGTH_SHORT)

if context is null.

Correct:

Toast.makeText(requireContext(), "Hello", Toast.LENGTH_SHORT).show()

Conclusion

Toast is one of the easiest ways to display short messages in Android. It provides quick feedback without interrupting the user and is useful for confirmations, status messages, and lightweight notifications.

Key takeaways:

  • Use Toast.makeText() for simple messages.
  • Choose between LENGTH_SHORT and LENGTH_LONG.
  • Use requireContext() inside Fragments.
  • Prefer string resources for localization.
  • Prevent multiple Toasts from stacking.
  • Consider Snackbar for modern Material Design apps.

Although Toast remains simple and effective, many modern Android applications prefer Snackbar because it offers better user interaction and follows Material Design guidelines.

About admin2

Check Also

Android Framework

Understanding the Android Framework: The Backbone of Android Development

Android powers billions of devices worldwide, from smartphones and tablets to TVs, wearables, and automotive …

Leave a Reply

Your email address will not be published. Required fields are marked *