Can I cancel previous Toast when I want to show an other Toast?

后端 未结 11 1377
粉色の甜心
粉色の甜心 2020-12-05 17:18

In my app, I construct a calendar widget for my activity, when I scroll it to previous or next month, I let it make a toast and show it.

The question is, the toast n

相关标签:
11条回答
  • 2020-12-05 17:49

    Here is the Code.

    final Toast toastobject = Toast.makeText(context, "This message will disappear when toast.close(); is called", Toast.LENGTH_SHORT);
    

    Now you can use the Object of toastobject. Its Reference

    toastobject.cancel();
    

    You can use it in Thread or whenever you would like to Close the Toast.

    0 讨论(0)
  • 2020-12-05 17:52

    You need to call method on correct object.

    toastObject.cancel()
    
    0 讨论(0)
  • 2020-12-05 17:52

    You can reuse a toast, this will make it display immediately.

    myToast.setText(toastMsg);
    myToast.show();
    
    0 讨论(0)
  • 2020-12-05 17:53

    There are many ways by which we can cancel previous Toast when we want to show another Toast. below I have written a simplest an easy way to implement it. First of all, we have to create a variable which can be accessed in the whole class.

    private Toast toast;
    

    After creating the variable which can be accessed by whole class we have to create a method in our class which displays the toast message and checks if the previous toast is displaying then cancel it.

       public void showToast(String message) {
        if (toast != null) {
            toast.cancel();
        }
        toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
        toast.show();
    }
    

    you can change toast message by runtime calling above method.

    showToast("message 1");
    

    //after some time

    showToast("message 2");
    

    hope it helps.

    0 讨论(0)
  • 2020-12-05 17:53

    You can create static method and use it to show a toast:

    public static Toast toast = null;
    public static showToast(Context context,String msg){
    if(toast!=null)             //this will cancel the toast on the screen if one exists
       toast.cancel();
    toast = Toast.makeText(context,msg);
    toast.show();
    }
    
    0 讨论(0)
  • 2020-12-05 17:54

    You just need to declare a "Toast" var like this:

    Toast toastMessage;
    

    Then in your function, do it like this:

    if (toastMessage!= null) {
        toastMessage.cancel();
    }
    toastMessage= Toast.makeText(context, "The message you want to display", duration);
    toastMessage.show();
    
    0 讨论(0)
提交回复
热议问题