Godwin Godwin - 1 year ago 154
Android Question

how to customize snackBar's layout?

Is there any method to change the layout of a snackBar to custom View?

Now it comes black and we can change the background color.
But I don't know the right way to inflate a new layout and making it as snackBars background?


Answer Source

The Snackbar does not allow you to set a custom layout. However, as Primoz990 suggested you can get the Snackbar's View. The getView function returns the Snackbar.SnackbarLayout, which is a horizontal LinearLayout object whose children are a TextView and a Button. To add your own View to the Snackbar, you just need to hide the TextView, and add your View to the Snackbar.SnackbarLayout.

// Create the Snackbar
Snackbar snackbar = Snackbar.make(containerLayout, "", Snackbar.LENGTH_LONG);
// Get the Snackbar's layout view
Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) snackbar.getView();
// Hide the text
TextView textView = (TextView) layout.findViewById(android.support.design.R.id.snackbar_text);

// Inflate our custom view
View snackView = mInflater.inflate(R.layout.my_snackbar, null);
// Configure the view
ImageView imageView = (ImageView) snackView.findViewById(R.id.image);
TextView textViewTop = (TextView) snackView.findViewById(R.id.text);

// Add the view to the Snackbar's layout
layout.addView(snackView, 0);
// Show the Snackbar
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download