Wednesday, July 3, 2024
HomeLanguagesJavaCustom Snackbars in Android

Custom Snackbars in Android

SnackBars plays a very important role in the user experience. The snack bar which may or may not contain the action button to do shows the message which had happened due to the user interaction immediately. So in this article, it’s been discussed how the SnackBars can be implemented using custom layouts. Have a look at the following image to get an idea of how can the custom-made SnackBars can be differentiated from the regular(normal) SnackBars. Note that we are going to implement this project using the Java language. 

Custom Snackbars in Android

Steps to Implement the Custom SnackBars in Android

Step 1: Create an empty activity project

Step 2: Working with the activity_main.xml file

  • The main layout here includes only one button which when clicked the custom SnackBar is to be shown.
  • Invoke the following code, in the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="HardcodedText">
 
    <Button
        android:id="@+id/showSnackbarButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:backgroundTint="@color/colorPrimary"
        android:text="SHOW SNACKBAR"
        android:textColor="@android:color/white" />
 
</RelativeLayout>


Output UI: Run on Emulator

Custom Snackbars in Android

Step 3: Creating a custom layout for Snackbar

  • Under layout folder create a layout for SnackBar which needs to be inflated when building the SnackBar under the MainActivity.java file.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:ignore="HardcodedText">
 
    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:elevation="4dp"
        app:cardBackgroundColor="@color/colorPrimaryDark"
        app:cardCornerRadius="4dp"
        app:cardPreventCornerOverlap="true"
        app:cardUseCompatPadding="true">
 
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="8dp">
 
            <ImageView
                android:id="@+id/imageView"
                android:layout_width="45dp"
                android:layout_height="45dp"
                android:layout_alignParentStart="true"
                android:src="@drawable/image_logo" />
 
            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="4dp"
                android:layout_toEndOf="@id/imageView"
                android:text="Lazyroar"
                android:textAlignment="center"
                android:textColor="@android:color/white"
                android:textSize="18sp"
                android:textStyle="bold" />
 
            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/textView1"
                android:layout_marginStart="4dp"
                android:layout_toEndOf="@id/imageView"
                android:text="Computer Science Portal"
                android:textColor="@android:color/white"
                android:textSize="14sp" />
 
            <!--this view separates between button and the message-->
            <View
                android:layout_width="2dp"
                android:layout_height="45dp"
                android:layout_toStartOf="@id/gotoWebsiteButton"
                android:background="@android:color/white" />
 
            <Button
                android:id="@+id/gotoWebsiteButton"
                style="@style/Widget.MaterialComponents.Button.TextButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:text="GOTO WEBSITE"
                android:textColor="@android:color/white"
                android:textSize="14sp" />
 
        </RelativeLayout>
 
    </androidx.cardview.widget.CardView>
</RelativeLayout>


Which produces the following view:

Custom Snackbars in Android

Step 4: Working with the MainActivity.java file

Java




import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.material.snackbar.Snackbar;
 
public class MainActivity extends AppCompatActivity {
 
    Button bShowSnackbar;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // register the button with appropriate ID
        bShowSnackbar = findViewById(R.id.showSnackbarButton);
 
        bShowSnackbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
 
                // create an instance of the snackbar
                final Snackbar snackbar = Snackbar.make(v, "", Snackbar.LENGTH_LONG);
 
                // inflate the custom_snackbar_view created previously
                View customSnackView = getLayoutInflater().inflate(R.layout.custom_snackbar_view, null);
 
                // set the background of the default snackbar as transparent
                snackbar.getView().setBackgroundColor(Color.TRANSPARENT);
 
                // now change the layout of the snackbar
                Snackbar.SnackbarLayout snackbarLayout = (Snackbar.SnackbarLayout) snackbar.getView();
 
                // set padding of the all corners as 0
                snackbarLayout.setPadding(0, 0, 0, 0);
 
                // register the button from the custom_snackbar_view layout file
                Button bGotoWebsite = customSnackView.findViewById(R.id.gotoWebsiteButton);
 
                // now handle the same button with onClickListener
                bGotoWebsite.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getApplicationContext(), "Redirecting to Website", Toast.LENGTH_SHORT).show();
                        snackbar.dismiss();
                    }
                });
 
                // add the custom snack bar layout to snackbar layout
                snackbarLayout.addView(customSnackView, 0);
                 
                snackbar.show();
            }
        });
    }
}


Kotlin




import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.material.snackbar.Snackbar;
 
class MainActivity : AppCompatActivity() {
    var bShowSnackbar: Button? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // register the button with appropriate ID
        bShowSnackbar = findViewById(R.id.showSnackbarButton)
        bShowSnackbar.setOnClickListener(object : OnClickListener() {
            fun onClick(v: View?) {
 
                // create an instance of the snackbar
                val snackbar = Snackbar.make(v, "", Snackbar.LENGTH_LONG)
 
                // inflate the custom_snackbar_view created previously
                val customSnackView: View =
                    layoutInflater.inflate(R.layout.custom_snackbar_view, null)
 
                // set the background of the default snackbar as transparent
                snackbar.view.setBackgroundColor(Color.TRANSPARENT)
 
                // now change the layout of the snackbar
                val snackbarLayout = snackbar.view as SnackbarLayout
 
                // set padding of the all corners as 0
                snackbarLayout.setPadding(0, 0, 0, 0)
 
                // register the button from the custom_snackbar_view layout file
                val bGotoWebsite: Button = customSnackView.findViewById(R.id.gotoWebsiteButton)
 
                // now handle the same button with onClickListener
                bGotoWebsite.setOnClickListener(object : OnClickListener() {
                    fun onClick(v: View?) {
                        Toast.makeText(
                            applicationContext,
                            "Redirecting to Website",
                            Toast.LENGTH_SHORT
                        ).show()
                        snackbar.dismiss()
                    }
                })
 
                // add the custom snack bar layout to snackbar layout
                snackbarLayout.addView(customSnackView, 0)
                snackbar.show()
            }
        })
    }
}
//This code is written by Ujjwal kumar Bhardwaj


Output: Run on Emulator

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments