Show a snackbar to a menu click event in Android

Change

Snackbar.make("???", ....)

to

Snackbar.make(getWindow().getDecorView(), .....);

You must pass in a View to the Snackbar's static make method.

EDIT:

On some devices the snackbar can appear below the system's controls menu, and for that reason you may wanna call findViewById(android.R.id.content) to display the snackbar correctly:

Snackbar.make(getWindow().getDecorView().findViewById(android.R.id.content), .....);

This is how you show Snackbar on menu item click:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        Snackbar.make(this.findViewById(R.id.action_settings), "Pressed Setting", Snackbar.LENGTH_LONG).show();
    }
    if (id == R.id.help_settings) {
        Snackbar.make(this.findViewById(R.id.help_settings), "Pressed Help", Snackbar.LENGTH_LONG).show();
    }
    return super.onOptionsItemSelected(item);
}

this worked for me thx, I was missing the .show()

Snackbar.make(getCurrentFocus(),"settings clicked",Snackbar.LENGTH_LONG).show();

Tags:

Java

Android