A snackbar is a small banner that appears at the bottom of the screen. A snackbar provides a short message about running processes and automatically disappears after a few seconds.
Firstly, we need to add the Material Components dependency in the module's build.gradle
file.
dependencies {
// Other dependencies
// ...
implementation 'com.google.android.material:material:1.2.0'
}
In the layout XML file, we added a Button
that will be used to display a snackbar. A parent view is required to create a snackbar. So we add the android:id
attribute in the root layout.
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Open" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
The method Snackbar.make()
is used to create a snackbar. The last parameter is duration, which defines how long to display a snackbar.
Value | Description |
---|---|
LENGTH_SHORT | A snackbar will be shown for 1500 milliseconds. |
LENGTH_LONG | A snackbar will be shown for 2750 milliseconds. |
LENGTH_INDEFINITE | A snackbar will be shown until it is dismissed, or another snackbar is shown. |
duration | Custom duration in milliseconds. |
The method show()
is used to display a snackbar.
package com.example.app
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity()
{
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
myButton.setOnClickListener { showSnackbar() }
}
private fun showSnackbar()
{
val snack = Snackbar.make(rootLayout, "Hello world", Snackbar.LENGTH_LONG)
snack.show()
}
}
Leave a Comment
Cancel reply