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.
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 ).
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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With