Toast and Duration

I have a button in my activity. If I click on the Toast show. But when I click Toast show again. Therefore, as a result, when I click many times, this toast will appear for a long time. When it first disappears, the next one appears, etc. How can I do, when I press the button again, the first toast will be hidden.

+3
source share
2 answers

call the cancel()method to hide Toast if it is already displayed.

Check out this API.

This can simply be called in the Toast object.

Toast toast = new Toast(context);

toast.setText("Text");
toast.show();//(call show()  to display Toast)
toast.cancel();//(call cancel() to  hide Toast).
+5
source

Add this code to your activity (global toast) and cancel it if you want to show new text.

Toast myLovelyToastThatNeverDies;
public void onClick(View v) {

    if(myLovelyToastThatNeverDies==null)
        myLovelyToastThatNeverDies = new Toast(Activity.this);
    else
        myLovelyToastThatNeverDies.cancel();
    myLovelyToastThatNeverDies.setText("my new text");
    myLovelyToastThatNeverDies.setDuration(anAverageDuration);
    myLovelyToastThatNeverDies.show();
}
+3
source

All Articles