Reputation: 4304
I'm using Toast
to show some information to the user, because I want to show the newest message without delay, regardless of the previous messages. I do it like this (learned from old projects):
public class MainActivity extends Activity {
private Toast mToast;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
}
private void toast(final String message) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mToast.setText(message);
mToast.show();
}
});
}
}
That is, the single Toast
object is reused and showed multiple times, whenever I need show a new message, I just setText
and show
it again. It seems working fine, but after I did some searching on Google, I found most people will do it like this:
private void toast(final String message) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mToast.cancel();
mToast = Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT);
mToast.show();
}
});
}
Which cancel
s the previous Toast and then makes a new one by Toast.makeText
.
Are there any differences? Which one should I prefer?
Upvotes: 2
Views: 2810
Reputation: 25320
You should try to code something like this to avoid visibility of multiple toasts at a time.
private void toast(final String message) {
try{ mToast.getView().isShown(); // True if visible
mToast.setText(message);
} catch (Exception e) { // Invisible if exception
mToast = Toast.makeText(theContext, message, toastDuration);
}
mToast.show(); // Finally display it
}
Code help me is here.
Upvotes: 0
Reputation: 5451
You can cache the current Toast in the Activity's variable, and then cancel it just before showing the 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 the 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();
}
Upvotes: 1
Reputation: 57
Firstly, you have to create a function for your Toast and use that function as per your requirements.
Your solution is here.
Upvotes: 0
Reputation: 36
It is better use cancel() before showing the same toast. Better close the lifecycle of the toast to prevent a bug.
This method closes the view if it's showing, or doesn't show it if it isn't showing yet. You do not normally have to call this. Normally the view will disappear on its own after the appropriate duration.
Upvotes: 0