Alan Ford
Alan Ford

Reputation: 375

Show Toast if there is no Toast already showing

I have several buttons that can be clicked on a fragment. After clicking each button I show a Toast message that is exactly the same for each button. Thus if you press 5 different buttons one after another you will layer up 5 toast messages which will end up showing the same message for a long time. What I want to do is show a Toast if there is no Toast currently running.

The method that I use to show the Toast message

public void showToastFromBackground(final String message) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
            }
        });
    }

When a button is pressed I simply call showToastFromBackground("Text to show");.

What I actually want is something like

public void showToastFromBackground(final String message) {
    if(toastIsNotAlreadyRunning)
    {
        runOnUiThread(new Runnable() {

        @Override
        public void run() {
            Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
        }
    });
    }       
}

Upvotes: 2

Views: 4302

Answers (2)

Juanjo Vega
Juanjo Vega

Reputation: 1430

Use:

toast.getView().isShown();

Or:

if (toast == null || toast.getView().getWindowVisibility() != View.VISIBLE) {
    // Show a new toast...
}

EDIT:

Toast lastToast = null; // Class member variable

public void showToastFromBackground(final String message) {
    if(isToastNotRunning()) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                lastToast = Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG);
                lastToast.show();
            }
        });
    }       
}

boolean isToastNotRunning() {
    return (lastToast == null || lastToast.getView().getWindowVisibility() != View.VISIBLE);
}

Upvotes: 4

Jemshit
Jemshit

Reputation: 10038

Try isShown(). It returns a fatal error if no toast is shown. So you can use try and catch the error.

//"Toast toast" is declared in the class

 public void showAToast (String st){ 
        try{ 
            toast.getView().isShown();     // true if visible
            toast.setText(st);
        } catch (Exception e) {         // invisible if exception
            toast = Toast.makeText(theContext, st, toastDuration);
        }
        toast.show();  //finally display it
 }

From here.

This does not wait if there is toast already, then show. But it does change active toast's text and show new one immediately without toasts overlapping each other.

Upvotes: 2

Related Questions