0

I want to remove stacked Android Toasts after the user goes to another Fragment. I have Fragments that are stacked and in every Fragment, I have two buttons which triggers different Toast message. When operations of a Fragment is done and the user navigates to another Fragment or press back button Toasts are kept showing. This mainly happens when the user clicks buttons too fast and force Toasts to stack.

Or when I instantiate global Toast objects and call cancel() than both of toasts stop from showing in that lifecycle of a fragment no matter how many times the user tap button.

toast1 = new Toast(getContext());
toast2 = new Toast(getContext());
showFirstToast(toast1).show();
showSecondToast(toast2).show();

private Toast showFirstToast(Toast toast){
    LayoutInflater inflater = getLayoutInflater();
    View layout = inflater.inflate(R.layout.toast_layout_correct, (ViewGroup) 
                                   getActivity().findViewById(R.id.toast_layout));
    toast.setDuration(Toast.LENGTH_SHORT);
    toast.setView(layout);
    return toast;
}
Ivan Z.
  • 59
  • 1
  • 10
  • 1
    Toasts are meant for system/critical type messages, so in proper usage, you would not want them to disappear when navigating somewhere else. The alternative is to use SnackBar, which would go away when you navigate away. – Tenfour04 Apr 09 '20 at 19:05
  • Thats the thing probably as I am trying to use Toast to notify completion of the process. Is SnackBars aperance animation costumizable? I want it to fade in/out same as Toast. – Ivan Z. Apr 09 '20 at 19:21
  • 1
    Looks like yes, with `setAnimationMode(BaseTransientBottomBar.ANIMATION_MODE_FADE)`. – Tenfour04 Apr 09 '20 at 19:49
  • And it can be positioned anywhere on View? – Ivan Z. Apr 09 '20 at 20:01
  • See here: https://stackoverflow.com/questions/31492351/how-can-you-adjust-android-snackbar-to-a-specific-position-on-screen – Tenfour04 Apr 09 '20 at 20:45

2 Answers2

1

Do not use global Toast object instead you should use multiple instances of Toast. So, you can cancel it one by one.

toast1 = new Toast(getContext());
toast2 = new Toast(getContext());
showFirstToast(toast).show();
showSecondToast(toast).show();

toast1.cancel()

bvarga
  • 716
  • 6
  • 12
  • I have tried that also, and still, the problem persists. I've edited the question for better understanding. – Ivan Z. Apr 09 '20 at 18:51
1

to avoid stacked toasts I reuse a single toast

Toast toast;

protected void showToast(final String text) {
    if (toast == null)
        toast = Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT);
    else
        toast.setText(text); // smoother transition than cancel + new toast
    toast.show();
}

@Override
public void onPause() {
    if(toast != null)
        toast.cancel();
    super.onPause();
}
kai-morich
  • 427
  • 2
  • 7