Toasts in Android: A Complete Guide with Sample Code

In Android development, Toasts are simple pop-up messages that provide feedback to the user about an operation or event. Toasts are lightweight and non-intrusive, displaying a brief message for a short duration before disappearing automatically. Toasts are ideal for showing quick feedback like confirmation of an action, a success message, or a short error notification.

In this article, we’ll cover how to implement Toasts in Android Studio, customize them, and provide sample code for better understanding.

What is a Toast in Android?

A Toast is a small message that pops up at the bottom of the screen, overlaying the current activity. Toast messages do not block user interaction, and they disappear after a set time period. They are typically used for lightweight feedback, such as “Item added to cart” or “Settings updated.”

Characteristics of a Toast:

  • Duration: Toasts can be shown for a short or long duration.
  • Non-interactive: Users cannot interact with a Toast; it’s just a passive notification.
  • Placement: By default, Toasts appear at the bottom of the screen, but you can customize their position.

Creating a Simple Toast

The simplest form of a Toast in Android is created using the Toast.makeText() method, followed by calling show() to display it.

Basic Toast Example:

Toast.makeText(context, "This is a simple toast message!", Toast.LENGTH_SHORT).show()

Explanation:

  • context: Refers to the current context (e.g., activity or application context).
  • "This is a simple toast message!": The message displayed in the toast.
  • Toast.LENGTH_SHORT: The duration of the Toast (can be either Toast.LENGTH_SHORT or Toast.LENGTH_LONG).
  • show(): This method is called to actually display the Toast.

Usage in an Activity:

Here’s how you can display a Toast within an Activity:

class MainActivity : AppCompatActivity() {

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

        // Show a toast when the activity is created
        Toast.makeText(this, "Welcome to the app!", Toast.LENGTH_LONG).show()
    }
}

In this example, the toast “Welcome to the app!” will be shown when the app launches.

Toast Duration

Android provides two predefined durations for a Toast:

  • Toast.LENGTH_SHORT: Displays the Toast for a short duration (roughly 2 seconds).
  • Toast.LENGTH_LONG: Displays the Toast for a longer duration (roughly 3.5 seconds).

Example:

// Short duration toast
Toast.makeText(this, "Short duration toast", Toast.LENGTH_SHORT).show()

// Long duration toast
Toast.makeText(this, "Long duration toast", Toast.LENGTH_LONG).show()

Customizing Toast Position

By default, a Toast appears at the bottom of the screen. However, you can adjust the position of the Toast using the setGravity() method.

Custom Positioning Example:

val toast = Toast.makeText(this, "This toast is at the top!", Toast.LENGTH_SHORT)
toast.setGravity(Gravity.TOP, 0, 0)
toast.show()

Explanation:

  • setGravity(Gravity.TOP, 0, 0): This method allows you to set the position of the toast. The first parameter controls the placement (Gravity.TOP, Gravity.CENTER, etc.), while the second and third parameters define the X and Y offsets for fine-tuning the position.

You can place the Toast in other areas like the center or bottom-right corner by adjusting the Gravity values and the offsets.

Example to position the Toast in the center:

Custom Toasts with Layouts

If you want to customize a Toast further (such as adding images, changing background colors, or using custom layouts), you can create a custom Toast using XML layout files.

Step-by-Step: Creating a Custom Toast

  1. Create a Custom Layout: Create an XML layout for the custom Toast in the res/layout folder (e.g., custom_toast.xml).
<!-- res/layout/custom_toast.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="8dp"
    android:background="@android:color/holo_blue_light">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@android:drawable/ic_dialog_info"
        android:contentDescription="icon" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="8dp"
        android:text="Custom Toast Message"
        android:textColor="@android:color/white"
        android:textSize="16sp" />
</LinearLayout>
  1. Inflate the Custom Layout and Create the Toast:

In your Activity, you can inflate the custom layout and display the Toast like this:

class MainActivity : AppCompatActivity() {

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

        // Inflate the custom toast layout
        val inflater: LayoutInflater = layoutInflater
        val layout: View = inflater.inflate(R.layout.custom_toast, findViewById(R.id.custom_toast_container))

        // Create the custom toast
        val toast = Toast(applicationContext)
        toast.duration = Toast.LENGTH_LONG
        toast.view = layout // Set the custom view for the toast
        toast.show()
    }
}

In this example:

  • LayoutInflater: Used to inflate the custom layout.
  • findViewById(R.id.custom_toast_container): You need to have a root element in your custom XML layout with this ID.
  • toast.view = layout: This assigns the custom layout to the Toast object.

Now, when the activity starts, the custom Toast will be displayed with the defined layout, which includes an icon and a message.

Dismissing Toasts Programmatically

One limitation of standard Android Toasts is that they cannot be dismissed programmatically once displayed. They disappear automatically after the set duration. If you need more control over the dismissal of notifications, consider using a Snackbar, which offers more interaction options.

Custom Toast Duration

The Toast duration is either short or long. There is no built-in method for setting a custom duration beyond these two predefined values. However, you can achieve a longer or more custom duration by showing the Toast multiple times using a Handler or Timer.

Example of Custom Toast Duration:

val toast = Toast.makeText(this, "Custom duration toast", Toast.LENGTH_SHORT)
val handler = Handler(Looper.getMainLooper())

// Repeat the toast for a custom duration (e.g., 5 seconds)
for (i in 0..4) {
    handler.postDelayed({ toast.show() }, (i * 1000).toLong())
}

In this example, the Toast is shown repeatedly every second, effectively creating a custom duration of 5 seconds.

Toast in Kotlin Coroutines (Asynchronous Toasts)

In modern Android development, Kotlin coroutines are widely used to handle asynchronous tasks. Toast messages can also be triggered in coroutine contexts when a background task completes.

Example with Kotlin Coroutines:

import kotlinx.coroutines.*

class MainActivity : AppCompatActivity() {

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

        // Launch a coroutine to show a toast after a background task
        GlobalScope.launch(Dispatchers.Main) {
            delay(2000)  // Simulate a background task (e.g., network call)
            Toast.makeText(this@MainActivity, "Task Completed!", Toast.LENGTH_SHORT).show()
        }
    }
}

Here, the Toast is displayed after a 2-second delay, simulating a task completion in a background thread.

Conclusion

Toasts are a simple yet effective way to provide feedback to users in Android applications. They offer flexibility in how you present messages, whether you’re using the default layout or creating a custom view for a more polished look. By understanding how to use Toasts

You may also like...

Leave a Reply

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