Skip to content Skip to sidebar Skip to footer

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 ti

Solution 1:

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();
}

Solution 2:

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.


Post a Comment for "Cancel Previously Shown Toast Before Showing New Toast"