Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show Snackbar when Activity starts?

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

like image 437
Sudheesh Mohan Avatar asked Oct 07 '22 22:10

Sudheesh Mohan


3 Answers

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();
}
like image 89
David Corsalini Avatar answered Oct 21 '22 11:10

David Corsalini


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()
like image 36
devDeejay Avatar answered Oct 21 '22 11:10

devDeejay


Try this

Snackbar.make(findViewById(android.R.id.content), "Got the Result", Snackbar.LENGTH_LONG)
                        .setAction("Submit", mOnClickListener)
                        .setActionTextColor(Color.RED)
                        .show();
like image 34
Mohammad Adil Avatar answered Oct 21 '22 11:10

Mohammad Adil