Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>keep track of the last time you showed the toast, and make re-showing it a no-op if it falls within some interval.</p> <pre><code>public class RepeatSafeToast { private static final int DURATION = 4000; private static final Map&lt;Object, Long&gt; lastShown = new HashMap&lt;Object, Long&gt;(); private static boolean isRecent(Object obj) { Long last = lastShown.get(obj); if (last == null) { return false; } long now = System.currentTimeMillis(); if (last + DURATION &lt; now) { return false; } return true; } public static synchronized void show(Context context, int resId) { if (isRecent(resId)) { return; } Toast.makeText(context, resId, Toast.LENGTH_LONG).show(); lastShown.put(resId, System.currentTimeMillis()); } public static synchronized void show(Context context, String msg) { if (isRecent(msg)) { return; } Toast.makeText(context, msg, Toast.LENGTH_LONG).show(); lastShown.put(msg, System.currentTimeMillis()); } } </code></pre> <p>and then,</p> <pre><code>RepeatSafeToast.show(this, "Hello, toast."); RepeatSafeToast.show(this, "Hello, toast."); // won't be shown RepeatSafeToast.show(this, "Hello, toast."); // won't be shown RepeatSafeToast.show(this, "Hello, toast."); // won't be shown </code></pre> <p>this isn't perfect, since the length of <code>LENGTH_SHORT</code> and <code>LENGTH_LONG</code> are undefined, but it works well in practice. it has the advantage over other solutions that you don't need to hold on to the Toast object and the call syntax remains terse.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload