A bug found during the product testing process is that after the tester repeatedly clicks a button and triggers toast, the toast content will always be displayed in the queue and cannot disappear quickly. This may affect your use.
Toast has a cancel () method:
Copy codeThe Code is as follows: void cancel ()
Close the view if it's showing, or don't show it if it isn' t showing yet.
As a programmer, you can see it from the api. You can use this to cancel the display of the previous toast and then display the next one to solve the problem. However, during the test, I found that it was not as simple as I imagined. If I believe it is not possible, I believe that the toast cancel () method does not work. Let's not talk about the specific process. Let's just talk about the results.
I made toast An application class for ease of use,You can directly use:
Copy codeThe Code is as follows: package com. arui. framework. android. util;
Import android. content. Context;
Import android. OS. Handler;
Import android. OS. logoff;
Import android. widget. Toast;
Copy codeThe Code is as follows :/**
* Toast util class.
*
* @ Author <A href = "http://jb51.net"> http://jb51.net </A>
* @ Version 2011/11/30
*
*/
Public class ToastUtil {
Private static Handler handler = new Handler (Looper. getMainLooper ());
Private static Toast toast = null;
Private static Object synObj = new Object ();
Public static void showMessage (final Context act, final String msg ){
ShowMessage (act, msg, Toast. LENGTH_SHORT );
}
Public static void showMessage (final Context act, final int msg ){
ShowMessage (act, msg, Toast. LENGTH_SHORT );
}
Public static void showMessage (final Context act, final String msg,
Final int len ){
New Thread (new Runnable (){
Public void run (){
Handler. post (new Runnable (){
@ Override
Public void run (){
Synchronized (synObj ){
If (toast! = Null ){
Toast. cancel ();
Toast. setText (msg );
Toast. setDuration (len );
} Else {
Toast = Toast. makeText (act, msg, len );
}
Toast. show ();
}
}
});
}
}). Start ();
}
Public static void showMessage (final Context act, final int msg,
Final int len ){
New Thread (new Runnable (){
Public void run (){
Handler. post (new Runnable (){
@ Override
Public void run (){
Synchronized (synObj ){
If (toast! = Null ){
Toast. cancel ();
Toast. setText (msg );
Toast. setDuration (len );
} Else {
Toast = Toast. makeText (act, msg, len );
}
Toast. show ();
}
}
});
}
}). Start ();
}
}
The logic of the code is simple. Synchronization is added here to ensure that the content of each toast can be displayed at least, rather than being canceled before being displayed. This is because the content of toast is not necessarily the same. If it is not displayed, it may also be a problem.