How to show Snackbar when Activity starts?

Sudheesh Mohan picture Sudheesh Mohan · Jun 22, 2015 · Viewed 122.9k times · Source

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)?

Answer

David Corsalini picture David Corsalini · Jun 22, 2015

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();
}