Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to immediately replace the current toast with a second one without waiting for the current one to finish? [duplicate]

I have many buttons. And on click of each of them I show a Toast. But while a toast loads and show in view, another button is clicked and the toast is not displayed until the one that is being displayed finishes.

So, I would like to sort out a way to detect if a toast is showing in the current context. Is there a way to know if a toast is being displayed such that I can cancel it and display a new one.

like image 374
Sandeep Avatar asked Jun 27 '11 17:06

Sandeep


People also ask

How do you avoid a toast if there's one toast already being shown?

How do you avoid a toast if there's one toast already being shown? It turned out by logging getDuration() that it carries a value of 0 (if makeText() 's parameter was Toast. LENGTH_SHORT ) or 1 (if makeText() 's parameter was Toast. LENGTH_LONG ).

How the position of a standard toast can be changed?

Positioning your Toast A standard toast notification appears near the bottom of the screen, centered horizontally. You can change this position with the setGravity(int, int, int) method. This accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.

How can I increase my toast time?

Actually, it is impossible to change these durations. However, we will use the existing duration Toast. LENGTH_LONG for displaying the Toast. Using this, a Toast can be displayed for 3.5 seconds.


1 Answers

You can cache current Toast in Activity's variable, and then cancel it just before showing next toast. Here is an example:

Toast m_currentToast;

void showToast(String text)
{
    if(m_currentToast != null)
    {
        m_currentToast.cancel();
    }
    m_currentToast = Toast.makeText(this, text, Toast.LENGTH_LONG);
    m_currentToast.show();

}

Another way to instantly update Toast message:

void showToast(String text)
{
    if(m_currentToast == null)
    {   
        m_currentToast = Toast.makeText(this, text, Toast.LENGTH_LONG);
    }

    m_currentToast.setText(text);
    m_currentToast.setDuration(Toast.LENGTH_LONG);
    m_currentToast.show();
}
like image 177
inazaruk Avatar answered Sep 18 '22 13:09

inazaruk