Skip to content
Related Articles

Related Articles

Improve Article

Snackbar in Android using Jetpack Compose

  • Last Updated : 26 Apr, 2021

Prerequisites:

Snackbar is a lightweight widget and they are used to show messages at the bottom of the application. It was introduced with the Material Design library as a replacement for a Toast.  In this article, we will explain how you can create a Snackbar using Jetpack Compose. Below is the sample picture to show what we are going to build. 

Step by Step Implementation

Step 1: Create a new project

To create a new project in Android Studio using Jetpack Compose please refer to How to Create a New Project in Android Studio Canary Version with Jetpack Compose. 



Step 2: Working with MainActivity.kt

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            JetpackComposePracticeTheme {
                // A surface container using the 'background' color from the theme
                Surface(color = Color.White) {
                    Column(modifier = Modifier.padding(10.dp)) {
                        // call the function which contains all the snackbars
                        SnackBars()
                    }
                }
            }
        }
    }
}
  
// In order to use compose properties annotate with @Compose
@Preview
@Composable
fun SnackBars() {
    Text(text = "Snackbars", style = typography.h6, modifier = Modifier.padding(8.dp))
    // Normal Snackbar
    Snackbar(modifier = Modifier.padding(4.dp)) {
        Text(text = "This is a basic snackbar")
    }
    // Snackbar with action item
    Snackbar(
        modifier = Modifier.padding(4.dp),
        action = {
            TextButton(onClick = {}) {
                Text(text = "Remove")
            }
        }
    ) {
        Text(text = "This is a basic Snackbar with action item")
    }
  
   // Snackbar with action item below text
    Snackbar(
        modifier = Modifier.padding(4.dp),
        actionOnNewLine = true,
        action = {
            TextButton(onClick = {}) {
                Text(text = "Remove")
            }
        }
    ) {
        Text(text = "Snackbar with action item below text")
    }
}

Output:

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!



My Personal Notes arrow_drop_up
Recommended Articles
Page :