简体   繁体   中英

Cancel previously shown toast before showing new toast

I have a function attached to a button that when pressed removes an item from an arraylist and then displays a toast saying "Item Removed!". If I press the remove button several times then ALL the toasts show up making it look like one really long toast display. I want to cancel the toast each time before displaying a new toast. I was displaying my toast as such

public void removeItem(View view)
{
    Toast.makeText(getApplicationContext(),"Text",toast.LENGTH_LONG).show();
}

Now I am trying to make a toast object, cancel it, set the text, and then display it each time the button is pressed. This way the previous toast is cancelled. Not sure if this is the right way to do it.

public void removeItem(View view)
{
    Toast toast = Toast.makeText(this,"",Toast.LENGTH_SHORT);
    toast.cancel();
    toast.setText("Text");
    toast.show();
}

This ends up showing nothing at all. Any help?

Your given example does not work because you are calling cancel() on the newly created instance of your Toast object. You'll have to keep a reference to the currently shown Toast somehow, and cancel it before displaying it again.

Toast mMyToast // declared within the activity class
public void removeItem(View view)
{
    if(mMyToast!=null) mMyToast.cancel() // Avoid null pointer exceptions!
    mMyToast = Toast.makeText(this,"Text",Toast.LENGTH_SHORT);
    mMyToast.show();
}

A couple of thoughts:

1: you could make the text more specific so that they can see which item was removed and they don't look like one long toast: "Removed Item: Bob", "Removed Item: Mary".

2: Make the toast display length short.

3: Consider skipping the toast all together. I assume they will see the items being removed from the list as you click.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM