Search code examples
androidandroid-layoutandroid-custom-viewandroid-snackbarsnackbar

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?

Thanks...


Solution

  • 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);
    textView.setVisibility(View.INVISIBLE);
    
    // Inflate our custom view
    View snackView = mInflater.inflate(R.layout.my_snackbar, null);
    // Configure the view
    ImageView imageView = (ImageView) snackView.findViewById(R.id.image);
    imageView.setImageBitmap(image);
    TextView textViewTop = (TextView) snackView.findViewById(R.id.text);
    textViewTop.setText(text);
    textViewTop.setTextColor(Color.WHITE);
    
    //If the view is not covering the whole snackbar layout, add this line
    layout.setPadding(0,0,0,0);
    
    // Add the view to the Snackbar's layout
    layout.addView(snackView, 0);
    // Show the Snackbar
    snackbar.show();