Best way to avoid Toast accumulation in Android

后端 未结 3 1978
日久生厌
日久生厌 2020-12-30 05:46

In Android, when I create Toast and show them, they appear consecutively. The problem is that I have a button that checks some fields and if the user enters incorrect data,

3条回答
  •  星月不相逢
    2020-12-30 06:08

    You can use the cancel() method of Toast to close a showing Toast.

    Use a variable to keep a reference to every Toast as you show it, and simply call cancel() before showing another one.

    private Toast mToast = null; // <-- keep this in your Activity or even in a custom Application class
    
    //... show one Toast
    if (mToast != null) mToast.cancel();
    mToast = Toast.makeText(context, text, duration);
    mToast.show();
    
    //... show another Toast
    if (mToast != null) mToast.cancel();
    mToast = Toast.makeText(context, text, duration);
    mToast.show();
    
    // and so on.
    

    You could even wrap that into a small class like so:

    public class SingleToast {
    
        private static Toast mToast;
    
        public static void show(Context context, String text, int duration) {
            if (mToast != null) mToast.cancel();
            mToast = Toast.makeText(context, text, duration);
            mToast.show();
        }
    }
    

    and use it in your code like so:

    SingleToast.show(this, "Hello World", Toast.LENGTH_LONG);
    

    //

提交回复
热议问题