Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel Toast created in a different method on android?

Tags:

android

toast

I have the following code:

private Toast movieRecordToast;

    private void displayNextMovie() {
        if (movieRecordToast != null) movieRecordToast.cancel(); // cancel previous Toast (if user changes movies too often)
        movieRecordToast = Toast.makeText(getApplicationContext(), "Next", Toast.LENGTH_SHORT);
        movieRecordToast.show();

    private void displayPrevMovie() {
        if (movieRecordToast != null) movieRecordToast.cancel();
        movieRecordToast = Toast.makeText(getApplicationContext(), "Prev", Toast.LENGTH_SHORT);
        movieRecordToast.show();        

But if displayNextMovie is called quickly several times and then displayPrevMovie is called, "Next" Toast is still shown and only after that "Prev" is displayed. Looks like cancellation doesn't work properly.

like image 714
LA_ Avatar asked Mar 31 '11 17:03

LA_


People also ask

How do I stop toast messages on android?

"Settings" > "Notifications" > under "Recently Sent", click "More" > then at the top, drop the list down to select "All" > and then just turn off the apps you don't want to see anything from at all. BTW, you don't have to wait for the toast to go away on its own.

How do I cancel toast?

Log into My Account to submit your cancellation request, or call 1-419-292-2200 during business hours. Once your cancellation is received you will be provided with a cancellation confirmation number which you should retain for your records. Your service will be active until the last day of the month.

How do I change the toast style in android?

Create a new instance of Toast using makeText() method. Use getView() method to get the view of the Toast. Open MainActivity. java file and add function to show toast message.

Which method is used to show toast on screen?

Use the makeText() method, which takes the following parameters: The application Context . The text that should appear to the user. The duration that the toast should remain on the screen.


1 Answers

Instead of creating a new Toast object each time you want a new text displayed you can easily hold on to only one Toast object and cancel the current Toast whenever you want. Before the next Toast is being displayed you can change text with Toast.setText() function.

Sample code:

private Toast mToastText;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Create the object once.
    mToastText = Toast.makeText(this, "", Toast.LENGTH_SHORT);
}

private void displayText(final String message) {
    mToastText.cancel();
    mToastText.setText(message); 
    mToastText.show();
}
like image 73
Wroclai Avatar answered Oct 27 '22 13:10

Wroclai