Most visited

Recently visited

Adding an Action to a Message

See Also

You can add an action to a Snackbar, allowing the user to respond to your message. If you add an action to a Snackbar, the Snackbar puts a button next to the message text. The user can trigger your action by pressing the button. For example, an email app might put an undo button on its "email archived" message; if the user clicks the undo button, the app takes the email back out of the archive.

Figure 1. This Snackbar has an Undo button, which restores the item that was just removed.

To add an action to a Snackbar message, you need to define a listener object that implements the View.OnClickListener interface. The system calls your listener's onClick() method if the user clicks on the message action. For example, this snippet shows a listener for an undo action:

public class MyUndoListener implements View.OnClickListener{

    &Override
    public void onClick(View v) {

        // Code to undo the user's last action
    }
}

Use one of the SetAction() methods to attach the listener to your Snackbar. Be sure to attach the listener before you call show(), as shown in this code sample:

Snackbar mySnackbar = Snackbar.make(findViewById(R.id.myCoordinatorLayout),
                                R.string.email_archived, Snackbar.LENGTH_SHORT);
mySnackbar.setAction(R.string.undo_string, new MyUndoListener());
mySnackbar.show();

Note: A Snackbar automatically goes away after a short time, so you can't count on the user seeing the message or having a chance to press the button. For this reason, you should consider offering an alternate way to perform any Snackbar action.

Hooray!