Snackbar
Snackbar in Material Design is an important component to show brief message about processing or actions in an application just like Toast but it is more useful than a Toast as it can contains one or more action button also which is lack in toast. You can only show text message using toast and it cannot be dismiss until the time limit but Snackbar can be swiped off before the time limit. Snackbars with an action are not self-dismissed until the user performs another action.
Also read How to create divider in jetpack compose
Toast
A Toast is android widget can be used to show a simple text feedback about an action in a small popup. It only fills the amount of space required for the message but limited to two lines of text and shows the application icon next to the text and the current activity remains visible and interactive.
Toasts automatically disappear after a timeout. If your app is in the background, and you want users to take some action, use a notification or in the foreground a Snackbar.
Snackbar
Copy this code →
//A simple Snackbar
package com.example.codingbihar
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch
@Composable
fun SnackBarSample() {
Box {
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
Button(modifier = Modifier.padding(100.dp),
onClick = {
scope.launch {
snackbarHostState.showSnackbar(
"Android Snackbar",
actionLabel = "Delete"
)
}
}
) {
Text(text = " Show Snackbar ")
}
SnackbarHost(hostState = snackbarHostState)
}
}
OUTPUT :-
Toast
Copy this code →
package com.example.codingbihar
import android.widget.Toast
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
@Composable
fun ToastSample() {
Box {
val context = LocalContext.current.applicationContext
Button(modifier = Modifier.padding(30.dp),
onClick = { Toast.makeText(context, "Android Toast", Toast.LENGTH_SHORT).show() }) {
Text(text = "Show Toast")
}
}
}