Display Toast on Button Click – Android Jetpack Compose

Display Toast on Button Click in Android Jetpack Compose

To display text when user clicks on the Button, write Toast code in the onClick parameter code block.

A sample code snippet is given below.

Button(
    onClick = {
        Toast.makeText(
            context,
            "You clicked the button.",
            Toast.LENGTH_LONG)
            .show()
    }
) {
    Text(text = "Click Me")
}

When user clicks or presses on the Button, the Toast is displayed as shown in the following screenshot.

Display Toast on Button Click in Android Jetpack Compose

Example Android application with Button onClick

Let us display a Button in the Android UI, using Button composable. When user clicks on the button, we shall display the Toast.

MainActivity.kt

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.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
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 {
                Column(
                    modifier = Modifier.fillMaxWidth().padding(vertical = 20.dp),
                    horizontalAlignment = Alignment.CenterHorizontally) {
                    val context = LocalContext.current
                    Button(
                        onClick = {
                            Toast.makeText(
                                context,
                                "You clicked the button.",
                                Toast.LENGTH_LONG)
                                .show()
                        }
                    ) {
                        Text(text = "Click Me")
                    }
                }
            }
        }
    }
}

Screenshot

Display Toast on Button Click in Android Jetpack Compose
Android UI with Button composable

Click on the Click Me button

Display Toast on Button Click in Android Jetpack Compose
Toast displayed when user clicks on the button