1

I'm working on my first Android application and I have a situation that really annoys me.

Lets say that user has to enter some information in few Edit Text fields and can't proceed if there is at least one empty field.

If user clicks a button to proceed and there is at least one empty field, a certain Toast is displayed.

The problem is, if user clicks that button like 10 times, and then enters those missing information and proceeds, those Toast messages keep showing in the new Activity along with Toast for successful registration.

Is there a way to interrupt a currently displayed Toast and display newest or something similar that will stop this kind of behaviour from happening?

edit: I have accepted @Vucko's answer because it suits better for my problem. @Augusto Carmo wrote the answer that indeed works, but I prefer Vucko's answer, it is just more elegant.

CleanCoder265
  • 574
  • 1
  • 5
  • 22
  • 3
    Heard about `editText.setError("Yo bro enter something");`? That is way better than a toast and it'll automatically solve your error. – Vucko Aug 28 '16 at 21:42
  • @Vucko No, I haven't, till now. Thanks for the help. – CleanCoder265 Aug 28 '16 at 21:52
  • Take a look at [question](http://stackoverflow.com/questions/5907863/how-to-check-if-the-toast-have-dismissed-or-not) and [this question](http://stackoverflow.com/questions/5295765/toast-issue-in-android) as well. – Kolten Sturgill Aug 28 '16 at 21:53
  • 1
    @KoltenSturgill those answers would solve this situation, but I wasn't aware of setError method, and it just seems more appropriate solution for this kind of problem. I would say that setError is probably more friendly for device resource usage. Thanks tho! – CleanCoder265 Aug 28 '16 at 22:00

2 Answers2

3

Have a single Toast object, and when you want to show another toast message, you cancel the last one and show the new one. Example:

Toast toast = new Toast();
toast.makeText(CONTEXT_HERE, MESSAGE_HERE, TIME_HERE).show();

// displaying another
toast.cancel();
toast.makeText(CONTEXT_HERE, ANOTHER_MESSAGE_HERE, TIME_HERE).show();
Augusto Carmo
  • 4,386
  • 2
  • 28
  • 61
3

The more elegant and common way to do this would be to use:

editText.setError("Your error message");

This will disappear itself once you write something in your editText or you can manually remove it by calling setError(null);.

Vucko
  • 7,371
  • 2
  • 27
  • 45