Reputation: 2258
I have a SnackBar
in Activity
A, if I click on a Button
in Activity
A I navigate to Activity
B. If I press back immediately, I can see the SnackBar
still being show in Activity
A.
How to make SnackBar
dismiss
once user leaves the Activity
.
My Effort:
Wrote a generic class which handles creation and dissmissal of SnackBar and
Create SnackBar :
public static Snackbar showSnackBar(View view, int text) {
if(snackBar != null && snackBar.isShown()) {
snackBar.setText(text);
} else {
snackBar = snackBar.make(view, text, Snackbar.LENGTH_LONG);
}
if (!AppRunningState.isApplicationBroughtToBackgrounds(App.get())) {
snackBar.show();
}
return snackBar;
}
and in onPause
:
@Override
protected void onPause() {
super.onPause();
SVSnackBar.dismissSnackBar();
}
public static void dismissSnackBar() {
if (snackBar != null) {
snackBar.dismiss();
}
}
Upvotes: 3
Views: 3698
Reputation: 113
Try this code. This should do the trick.
snackbar = Snackbar.make(loginView, text, Snackbar.LENGTH_LONG);
snackbar.setActionTextColor(getResources().getColor(R.color.colorAccent));
snackbar.setAction("Close", new View.OnClickListener() {
@Override
public void onClick(View v) {
snackbar.dismiss();
}
});
snackbar.show();
Here setAction() is optional. Need to use only if you want to close snackbar before the duration ends.
EDIT:
The issue your facing might because your calling your showSnackBar in onCreate method or within any of the methods that your calling in onCreate. Its just an assumption since you haven't given the entire code.
Upvotes: 0
Reputation: 1897
Well ... normally you just use one Snackbar for one Activity/layout. So one way to do it could be writing a BaseActivity holding a reference to a Snackbar.
public class BaseActivity extends Activity { // use the one you want to extend
private Snackbar snackbar;
public void showSnackbar(View view, int textResId) {
if (snackbar != null) {
snackbar.dismiss();
}
snackbar = Snackbar.make(view, textResId, Snackbar.LENGTH_LONG);
snackbar.show();
}
@Override
public void onPause() {
super.onPause();
if (snackbar != null) {
snackbar.dismiss();
}
}
}
Now always extend BaseActivity for every Activity you are using. It is basically the same thing you are doing but you do not need an extra class dealing with your Snackbar and you do not have to overwrite onPause() every time.
Upvotes: 4
Reputation: 1007544
Call dismiss()
on the Snackbar
when you start up the other activity.
Upvotes: 0