I'm using Toast
to show some informations 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
the previous Toast then make a new one by Toast.makeText
.
Are there any differences? Which one should I prefer?