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_SHORTorToast.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()aftermakeText(), 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
thisoractivityas context inside activities. - Choose
Toast.LENGTH_SHORTfor brief messages,Toast.LENGTH_LONGfor 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.