129

I want to show android Snackbar (android.support.design.widget.Snackbar) when the activity starts just like we show a Toast.

But the problem is we have to specify the parent layout when creating Snackbar like this:

Snackbar.make(parentlayout, "This is main activity", Snackbar.LENGTH_LONG)
            .setAction("CLOSE", new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                }
            })
            .setActionTextColor(getResources().getColor(android.R.color.holo_red_light ))
            .show();

How to give parent layout when we show Snackbar at the start of the activity without any click events (If it was a click event we could've easily pass the parent view)?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Sudheesh Mohan
  • 2,560
  • 3
  • 21
  • 38
  • 2
    Written an article to http://onetouchcode.com/2016/12/24/use-snackbar-android-apps/ , This will be helpful to know more details of Snackbar – Shailendra Dec 25 '16 at 13:47

11 Answers11

262

Just point to any View inside the Activity's XML. You can give an id to the root viewGroup, for example, and use:

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);    
   setContentView(R.layout.main_activity);
   View parentLayout = findViewById(android.R.id.content);
   Snackbar.make(parentLayout, "This is main activity", Snackbar.LENGTH_LONG) 
        .setAction("CLOSE", new View.OnClickListener() {
            @Override 
            public void onClick(View view) {

            } 
        }) 
        .setActionTextColor(getResources().getColor(android.R.color.holo_red_light ))
        .show(); 
   //Other stuff in OnCreate();
}
Ryan R
  • 8,342
  • 15
  • 84
  • 111
David Corsalini
  • 7,958
  • 8
  • 41
  • 66
  • 67
    For the root view, you can also generally use `findViewById(android.R.id.content)` as indicated here http://stackoverflow.com/a/4488149/1518546 – John Cummings Oct 30 '15 at 15:03
  • View parentLayout = findViewById(R.id.root_view); throws nullpointer exception in 5.0 or lower version. How to solve this problem ? – Anand Savjani Dec 31 '15 at 04:43
  • 1
    @AnandSavjani The code is working perfectly with me for 5.0 and below 5.0, there must be some error in your layout(root_view). If you are using fragment you should write rootview.findViewById(R.id.your_parent_view); And also dont give same id as layout name. – Sudheesh Mohan Jan 11 '16 at 10:07
  • I believe it throws NullpointerException if you are not using CoordinatorLayout as the root. – Ishaan Sep 07 '16 at 15:48
  • Don't forget to include the support design library : 'com.android.support:design:27.0.0' – Nikola Nov 26 '17 at 11:11
  • 'getColor()' deprecated in api 23. Use ContextCompat.getColor(context, R.color.color_name) instead. – Arpit Patel Nov 25 '20 at 14:11
52

I have had trouble myself displaying Snackbar until now. Here is the simplest way to display a Snackbar. To display it as your Main Activity Starts, just put these two lines inside your OnCreate()

    Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "Welcome To Main Activity", Snackbar.LENGTH_LONG);
    snackbar.show();

P.S. Just make sure you have imported the Android Design Support.(As mentioned in the question).

For Kotlin,

Snackbar.make(findViewById(android.R.id.content), message, Snackbar.LENGTH_SHORT).show()
devDeejay
  • 5,494
  • 2
  • 27
  • 38
11

Try this

Snackbar.make(findViewById(android.R.id.content), "Got the Result", Snackbar.LENGTH_LONG)
                        .setAction("Submit", mOnClickListener)
                        .setActionTextColor(Color.RED)
                        .show();
Mohammad Adil
  • 503
  • 6
  • 13
6

A utils function for show snack bar

fun showSnackBar(activity: Activity, message: String, action: String? = null,
    actionListener: View.OnClickListener? = null, duration: Int = Snackbar.LENGTH_SHORT) {
    val snackBar = Snackbar.make(activity.findViewById(android.R.id.content), message, duration)
        .setBackgroundColor(Color.parseColor("#CC000000")) // todo update your color
        .setTextColor(Color.WHITE)
    if (action != null && actionListener!=null) {
        snackBar.setAction(action, actionListener)
    }
    snackBar.show()
}

Example using in Activity

  showSnackBar(this, "No internet")
  showSnackBar(this, "No internet", duration = Snackbar.LENGTH_LONG)
  showSnackBar(activity, "No internet", "OK", View.OnClickListener { 
       // handle click 
  })

Example using in Fragment

  showSnackBar(getActivity(), "No internet")

Hope it help

Linh
  • 57,942
  • 23
  • 262
  • 279
4

call this method in onCreate

Snackbar snack = Snackbar.make(
                    (((Activity) context).findViewById(android.R.id.content)),
                    message + "", Snackbar.LENGTH_SHORT);
snack.setDuration(Snackbar.LENGTH_INDEFINITE);//change Duration as you need
            //snack.setAction(actionButton, new View.OnClickListener());//add your own listener
            View view = snack.getView();
            TextView tv = (TextView) view
                    .findViewById(android.support.design.R.id.snackbar_text);
            tv.setTextColor(Color.WHITE);//change textColor

            TextView tvAction = (TextView) view
                    .findViewById(android.support.design.R.id.snackbar_action);
            tvAction.setTextSize(16);
            tvAction.setTextColor(Color.WHITE);

            snack.show();
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
4

It can be done simply by using the following codes inside onCreate. By using android's default layout

Snackbar.make(findViewById(android.R.id.content),"Your Message",Snackbar.LENGTH_LONG).show();
Jarin Rocks
  • 975
  • 10
  • 17
  • on android version 5.x - suddenly `getWindow().getDecorView()` return ALL screen, include 'bottom buttons' (such home, back etc). So my snack was showing down to this buttons, not in app – alena_fox_spb Jan 17 '19 at 09:27
  • check the updated answer. It will solve your problem. Use android's default layout – Jarin Rocks Jan 17 '19 at 10:18
  • yes, when I changed from `window` to `android.R.id.content` all start work. So I wrote my comment to solve someones else issue with it in future) – alena_fox_spb Jan 17 '19 at 10:28
1

Simple way to show some text:

Snackbar.make(view, "<text>", Snackbar.LENGTH_SHORT).show();
// or
Snackbar.make(view, "<text>", Snackbar.LENGTH_LONG).show();

and to show text with a button:

Snackbar.make(view, "<text>", Snackbar.LENGTH_SHORT).setAction("<button_text>", new View.OnClickListener() {
            @Override 
            public void onClick(View view) {
                    // operation to perform when the button is clicked
            } 
        }).show();
Sid110307
  • 497
  • 2
  • 8
  • 22
0

You can try this library. This is a wrapper for android default snackbar. https://github.com/ChathuraHettiarachchi/CSnackBar

Snackbar.with(this,null)
    .type(Type.SUCCESS)
    .message("Profile updated successfully!")
    .duration(Duration.SHORT)
    .show();

This contains multiple types of snackbar and even a customview intergrated snackbar

0

You can also define a super class for all your activities and find the view once in the parent activity.

for example

AppActivity.java :

public class AppActivity extends AppCompatActivity {

    protected View content;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        changeLanguage("fa");
        content = findViewById(android.R.id.content);
    }
}

and your snacks would look like this in every activity in your app:

Snackbar.make(content, "hello every body", Snackbar.LENGTH_SHORT).show();

It is better for performance you have to find the view once for every activity.

M.Kasaei
  • 328
  • 6
  • 13
0

For those developers who use data binding in their project.

Snackbar.make(binding.getRoot(), "This is your text", Snackbar.LENGTH_LONG)
                        .setAction("CLOSE", view -> {
                            //close
                        })
                        .setActionTextColor(getResources().getColor(android.R.color.holo_red_light ))
                        .show();
M DEV
  • 763
  • 1
  • 7
  • 20
0

if you use Snackbar in Activity, use this code

View view = findViewById(android.R.id.content);

Snackbar.make(view, "Hello, world!", Snackbar.LENGTH_LONG).show();
Sid110307
  • 497
  • 2
  • 8
  • 22
  • Hello there! I suggest formatting your code. If you do not know how to, please refer to [this link](https://stackoverflow.com/help/formatting). Have a nice day! – JumperBot_ Jul 29 '22 at 04:29