Reputation: 750
I have 2 buttons and their onClick are connected to these methods a code similar to this:
/** Called when the user clicks button2 */
public void button1Start(View view) {
// Display a toast at bottom of screen
Toast.makeText(getApplicationContext(), "Toast1", Toast.LENGTH_SHORT).show();
}
/** Called when the user clicks button2 */
public void button2Start(View view) {
// Display different toast at bottom of screen
Toast.makeText(getApplicationContext(), "Toast2", Toast.LENGTH_SHORT).show();
}
Now, as expected when I click on these buttons, the toasts appear on bottom of screen one at a time after the previous one times-out.
What I need is this behavior: when I click button2 the "Toast2" view should immediately replace "Toast1" irrespective of the duration of "Toast1". Is there any way to achieve this? Can I make "toast1" to timeout or maybe make the toast1 view invisible?
Upvotes: 0
Views: 415
Reputation: 224
Just use the same Toast object to show your text.
Maybe you should create a singleton to use in your entire application, but the shortest way is:
private Toast mToast;
private void showMessage(String message) {
if (mToast == null) {
mToast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
} else {
mToast.setText(message);
}
mToast.show();
}
No need to cancel. The previous text is immediately replaced, if any.
Upvotes: 2
Reputation: 126445
How to make a toast timeout when another toast needs to be displayed?
Have you tried with cancel()
method?
Toast mytoast;
mytoast = Toast.makeText(getApplicationContext(), "Hi Ho Jorgesys! ", Toast.LENGTH_LONG);
mytoast.show();
....
....
....
if(CancelToast){
mytoast.cancel();
}
Upvotes: 0
Reputation: 1938
You can't make toast invisible, but you can make delay for it(but I think it's not a good practice)
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "Toast2", Toast.LENGTH_SHORT).show();
}
}, 100);
Upvotes: 0