Sudheesh Mohan Sudheesh Mohan - 14 days ago 6
Android Question

How to show Snackbar when Activity starts?

Hi everyone 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 aclick event we could've easily pass the parent view) ?

Answer

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(R.id.root_view);
   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();
}
Comments