Best way to avoid Toast accumulation in Android

后端 未结 3 1976
日久生厌
日久生厌 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:01

    Have only one Toast in this activity.

    private Toast toast = null;
    

    Then just check if there's currently a Toast being shown before creating another one.

    if (toast == null || !toast.getView().isShown()) {
        if (toast != null) {
            toast.cancel();
        }
        toast = Toast.makeToast("Your text", Toast.LENGTH).show();
    }
    

    You can even make that last snippet into a private method showToast(text) to refactor code if you need to display different text messages.

提交回复
热议问题