Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SnackBar still showing when I come back to previous Activity

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();
    }
}
like image 746
Logic Avatar asked Dec 15 '25 00:12

Logic


1 Answers

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.

like image 157
Jason Saruulo Avatar answered Dec 16 '25 13:12

Jason Saruulo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!