Dismiss active snack bar on Fragment destroy

Viewed 2850

How can I make sure any visible Snackbar (specially those with snackbar.length_indefinite) will be dismissed once fragment is destroyed?

Should I use a common globar variable for all Snackbars and call dismiss on that? Something like below?

Fragment1.java

private Snackbar snackbar;

@Override
public onDestroy(){
    snackbar.dismiss();
}

public Method1(){
    snackbar = Snackbar.make(ActivityMain.coordinatorLayout, "Text 1", snackbar.length_indefinite);
    snackbar.show();
}

public Method2(){
    snackbar = Snackbar.make(ActivityMain.coordinatorLayout, "Text 2", snackbar.length_indefinite);
    snackbar.show();
}
//coordinatorLayout is a static variable in ActivityMain which stores reference to the CoordinatorLayout
2 Answers

While having global SnackBar and making sure that you close it in onDestroyView() is a fine approach.

I suggest wrapping your Fragment XML layout in the CoordinatorLayout and passing the fragment root view to the Snackbar.make function, like so:

fragment_your_fragment.xml

<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<!-- Your Layout Content  -->

</androidx.coordinatorlayout.widget.CoordinatorLayout>

YourFragment.kt

fun showSnackbar() {
    Snackbar.make(requireView(), "Your message", Snackbar.LENGTH_INDEFINITE).show()
}

This way, when you open another fragment(add it to the stack), Snackbar will be dismissed automatically

Related