Stop all toast messages when going to another screen in Android

强颜欢笑 提交于 2019-11-27 05:22:10
Mojo Risin

Hi I have the same problem. The problem is that the Toast overlaps e.g. if you press 10 times the Toast will stay 10 x LENGTH_SHORT. The only solution I came with was to control the time the Toast is shown by myself. When you show a Toast just keep a track of the last time you show it, it's still on the screen don't show it again. In your worst case the Toast will be visible only LENGTH_SHORT time.

Toast.makeText returns a Toast object. You can call cancel() on this object to cancel it, then show the new one.

P Kuijpers

This simple solution works perfectly for me, a singleton which cancels any currently shown toasts:

public enum SingleToast {
    INSTANCE;

    private Toast currentToast;
    private String currentMessage;

    public void show(Context context, String message, int duration) {
        if (message.equals(currentMessage)) {
            currentToast.cancel();
        }
        currentToast = Toast.makeText(context, message, duration);
        currentToast.show();

        currentMessage = message;
    }
}

If you'd like to cancel ANY Toast (even if the messages are different), you could leave out the whole currentMessage part and include currentToast != null as a check for cancelling.

Drawback of the first method is that when you start 2 different toasts (#1 & #2), you won't be able to cancel them anymore when you start #1: this happens because the singleton saved #2 as the 'current' even though it is not shown yet. So when you start #1 again it is still added to the queue of 2 Toasts: #1, #2, #1, and all will be shown.

So choose whatever of these 2 solutions fits your usecase, or extend this simple singleton with timers, guess that's what Mojo suggested.

Calling the toast is simple: I use it to show the message of some custom exceptions:

public abstract class CustomToastException extends Exception {
    public CustomToastException(String message) {
        super(message);
        SingleToast.INSTANCE.show(context, getMessage(), Toast.LENGTH_LONG);
    }
}

Note, in case anyone was wondering: I've raised a new question whether my solution does not cause any trouble: Static context saved in Application class and used in a singleton toast builder, does this create a memory leak?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!