How to Create Snackbar in Android Studio


Snackbar provides lightweight feedback about an operation. The message appears at the bottom of the screen on mobile and lower left on larger devices. Snackbar appears above all the elements of the screen. But no component is affected by it. Having a CoordinatorLayout in your view hierarchy allows Snackbar to enable certain features, such as swipe-to-dismiss and automatically moving of widgets. Snackbar is similar to Toast but the only major difference is that an action can be added with Snackbar.

Approach:

  1. Add the support Library in build.gradle file and add Material Design dependency in the dependencies section.It is a part of Material Design that’s why we have to add a dependency.
    dependencies {
        implementation 'com.google.android.material:material:1.2.1'
    }
  2. Now add the following code in the activity_main.xml file. It will create a button named Open Snackbar.

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/layout"
        tools:context=".MainActivity">
      
        <Button android:id="@+id/button" android:gravity="center" android:padding="20dp" android:textAllCaps="false" android:textSize="18sp" android:text="Open snackBar" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
      
    </RelativeLayout>
  3. Now add the following code in the MainActivity.java file. This will define the button and add a onClickListener to the button. In the onClickListener a Snackbar is created and is called. So whenever the button is clicked, the onClickListener creates a snackbar and calls it and the user sees the message. This snackbar contains an action and if clicked will show a toast.

    MainActivity.java

    package com.vishwaa.snackbardemo;
      
    import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.RelativeLayout; import com.google.android.material.snackbar.Snackbar;
      
    public class MainActivity extends AppCompatActivity {
      
        Button button; RelativeLayout relativeLayout;
      
        @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
      
            button = findViewById(R.id.button); relativeLayout = findViewById(R.id.layout); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar snackbar = Snackbar.make(relativeLayout, "This is snackbar", Snackbar.LENGTH_LONG); snackbar.show(); } }); } }

Output: 



Video Tutorial



Comments