Android cancel Toast when exiting the app and when toast is being shown

后端 未结 4 1109
独厮守ぢ
独厮守ぢ 2020-11-27 05:32

I have read about this kind of problem here but the answers don\'t seem to be working.

I show a Toast when user clicks a button. When the user continous

4条回答
  •  离开以前
    2020-11-27 06:03

    Try keeping the timestamp of the last toast, and don't allow any new toasts until a timeout period has elapsed.

    Something like:

    private static final long TOAST_TIMEOUT_MS = 2000; // tweak this constant
    
    private static long lastToastTime = 0;
    
    public void onButtonClicked() {
      long now = System.currentTimeMillis();
      if (lastToastTime + TOAST_TIMEOUT_MS < now) {
        Toast.makeText(...).show();
        lastToastTime = now;
      }
    }
    

    I wouldn't worry about a single toast sticking around for a second after the user exits the app -- this is a pretty standard behavior.

提交回复
热议问题