How to Show Toast Message in Android Jetpack Compose

By Mohammed Rashid •  November 19th, 2022 • 

Toast messages are commonly seen in Android apps. Toasts are useful for showing a short and straightforward feedback message to the users. Let’s learn how to create and show toast messages in Android using Jetpack Compose.

Let’s show a toast message when a button is pressed. You need to pass the context, text, and duration to show the toast message.

val context = LocalContext.current
    Button(onClick = { Toast.makeText(context,"This a simple toast tutorial!", Toast.LENGTH_LONG).show() }) {
        Text("Click here to show toast!")
    }

Following is the output.

Following is the complete example to show Android toast.

package com.example.myapplication

import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                Surface(
                    color = MaterialTheme.colors.background,
                    modifier = Modifier.padding(20.dp)
                ) {
                    ToastExample()
                }
            }
        }
    }
}


@Composable
fun ToastExample() {
    val context = LocalContext.current
    Button(onClick = { Toast.makeText(context,"This a simple toast tutorial!", Toast.LENGTH_LONG).show() }) {
        Text("Click here to show toast!")
    }
}


@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MyApplicationTheme {
        ToastExample()
    }
}

I hope this Jetpack Compose tutorial is helpful for you.

Mohammed Rashid

Keep Reading