Skip to content

Toast in Jetpack compose

  • by

1. Overview

In this article, we will learn to show Toast in Jetpack compose.

A toast is a message displayed on the screen as a small popup and appears on top of the main content of an activity and remains only for a short time period. It only occupies the amount of space required for the message and the present activity remains visible and interactive.

For example, the text “This is a Toast message” is a toast:

Toast in Jetpack compose
Android toast

2. Android toast in Jetpack compose


To show the Toast message in Kotlin, use the makeText() method of Toast. It takes the following parameters:

  1. Application or activity Context – You can use LocalContext.current to get the context within the Jetpack composable function
  2. Text to be shown
  3. Duration to show the text.

The duration can be:

  1. Toast.LENGTH_LONG – To show for a long period
  2. Toast.LENGTH_SHORT – To show for a short period.

To show the toast, call the show() function on the toast object.

For example, the below makeText method takes the application context, “This is a Toast message” text and duration Toast.LENGTH_SHORT.

val text = "This is a Toast message"
val duration = Toast.LENGTH_SHORT

val context = LocalContext.current

val toast = Toast.makeText(context, text, duration)
toast.show()

2.2. Jetpack compose Toast gravity

You can customize the position of the toast on the device screen using setGravity function.

toast.setGravity(Gravity.LEFT, 0, 0)

To place the content in the center of the screen, then you can use Gravity.CENTER as below:

 toast.setGravity(Gravity.CENTER, 0, 0)

2.3. Toast example

For example, the following code shows a toast when the user clicks on the IconButton element on the screen.

You can’t call the LocalContext.current inside the onClick method as we can invoke this only within a composable and onClick is not a composable function.

val context = LocalContext.current
IconButton(onClick = { Toast.makeText(context,"Clicked!!!!",Toast.LENGTH_SHORT).show() }) {
            Icon(Icons.Default.MoreVert, contentDescription = "Settings")
        }

3. Conclusion

To sum up, we learned to display the Android message in the Jetpack compose.

Leave a Reply

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