简体   繁体   中英

Show a snackbar to a menu click event in Android

I have a menu on android and want to show a simple snackbar anywhere after there was a click on a menu item. Whatever I put something else instead of "???" doesn't work. The whole app is from the Android studio default tab view template. This is the code I have:

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

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

Why is it behaving like that? And how can I fix it?

Change

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

to

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

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

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

I tried this, it worked with me

public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch (id) {
        case R.id.action_settings:
            Snackbar.make(getCurrentFocus(), "U Clicked Settings",Snackbar.LENGTH_LONG).setAction("Action", null).show();
            return true;
    }
}

这对我有用,我错过了.show()

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

tried this, it worked fine

Snackbar.make(findViewById(android.R.id.content), 
        "Pressed Settings", Snackbar.LENGTH_LONG).show()

For Androidx Fragment and Kotlin

getCurrentFocus() , findViewById() and getWindow() won't work directly.

To use those functions, first get the instance of Activity and then cast it to your activity (The one that contains the current fragment). For example:

Snackbar.make((activity as YourActivity).findViewById(R.id.action_settings), 
    "Pressed Settings", Snackbar.LENGTH_LONG).show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM