简体   繁体   中英

Android Studio cancelling Toast message for the new message to show

At first what I want is to cancel the current showing message in Toast for the new message to show so I search and found that I need to create an Toast Object to use the .Cancel method. So I create a toast object just below the line of MainActivity but I get error when i'm running the application. It says "Unfortunately, MyApp has stopped". Confirmed that the error is when declaring the toast object below the main activity, I got that by commenting out the declaration and it run without error. And in toast message what I want is to cancel the current message for the next message to show just when I want it. Because the default is that it use all the Toast duration before it show the next triggered message.

My question is why am I getting an error in that? And how can I cancel the current Toast message to show my new message. Thanks in advance!

heres the code in declaring of Toast object

public class MainActivity extends AppCompatActivity {

    Toast toastObject = Toast.makeText(this, "", Toast.LENGTH_LONG);

my toastShowMsg code:

public void toastShowMsg(String message) {
    Toast toastObject = Toast.makeText(this, "", Toast.LENGTH_LONG);
    toastObject.cancel();
    toastObject = Toast.makeText(this, message, Toast.LENGTH_LONG);
    toastObject.show();
}

You are instantiating a new Toast object when you write the line

Toast toastObject = Toast.makeText(this, "", Toast.LENGTH_LONG);

then when you call

toastObject.cancel();

you are cancelling the Toast that you have just created, which is empty.

Toast toastObject = Toast.makeText(this, "", Toast.LENGTH_LONG); <-- new Toast creation, set to toastObject
toastObject.cancel(); <--- cancelling the toastObject that you have just created

What you want to do is keep a reference to that first Toast you create and then cancel that. It would look something like this:

public YourActivity extends AppCompatActivity
{
    Toast toastObject;

    ...


public void toastShowMsg(String message) {
    if (toastObject != null)
        toastObject.cancel();
    toastObject = Toast.makeText(this, message, Toast.LENGTH_LONG);
    toastObject.show();
}

By adding a reference to toastObject at the top of your class, it will keep a reference to it when you run the toastShowMsg method again and will then cancel the appropriate Toast .

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