0
0
Android-kotlinHow-ToBeginner ยท 3 min read

How to Create Toast in Android: Simple Guide

To create a toast in Android, use the Toast.makeText() method with a context, message, and duration, then call .show() to display it. For example, Toast.makeText(this, "Hello Toast", Toast.LENGTH_SHORT).show() shows a short popup message.
๐Ÿ“

Syntax

The basic syntax to create a toast in Android is:

  • Context: Usually the current activity or application context.
  • Message: The text string to display.
  • Duration: How long the toast shows; use Toast.LENGTH_SHORT or Toast.LENGTH_LONG.
  • show(): Call this method to display the toast on screen.
kotlin
Toast.makeText(context, "Your message here", Toast.LENGTH_SHORT).show()
Output
A small popup message appears briefly on the screen with the given text.
๐Ÿ’ป

Example

This example shows how to create and display a toast message when a button is clicked in an Android activity.

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.buttonShowToast)
    button.setOnClickListener {
      Toast.makeText(this, "Hello Toast!", Toast.LENGTH_SHORT).show()
    }
  }
}
Output
When the button is tapped, a small popup with text 'Hello Toast!' appears briefly at the bottom of the screen.
โš ๏ธ

Common Pitfalls

Common mistakes when creating toasts include:

  • Not calling show() after makeText(), so the toast never appears.
  • Using a wrong context, like getApplicationContext() in some cases, which may cause the toast to not display properly.
  • Trying to show a toast from a background thread instead of the main UI thread.
kotlin
/* Wrong: Missing show() */
Toast.makeText(this, "Missing show", Toast.LENGTH_SHORT)

/* Correct: Call show() */
Toast.makeText(this, "Correct toast", Toast.LENGTH_SHORT).show()
Output
Only the correct toast with .show() will appear on screen.
๐Ÿ“Š

Quick Reference

Summary tips for creating toasts in Android:

  • Use Toast.makeText(context, message, duration).show() to display.
  • Use this or activity as context inside activities.
  • Choose Toast.LENGTH_SHORT for brief messages, Toast.LENGTH_LONG for longer display.
  • Always call show() to make the toast visible.
โœ…

Key Takeaways

Always call .show() after Toast.makeText() to display the toast.
Use the current activity context (e.g., this) for proper toast display.
Choose between Toast.LENGTH_SHORT and Toast.LENGTH_LONG for duration.
Avoid showing toasts from background threads; use the main UI thread.
Toasts provide quick, temporary messages without blocking user interaction.