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:
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 use it directly:
package com.arui.framework.android.util;import android.content.Context;import android.os.Handler;import android.os.Looper;import android.widget.Toast;
/** * Toast util class. * * @author http://blog.csdn.net/arui319 * @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() {@Overridepublic 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() {@Overridepublic 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.
---------------------------------------------------------------------------
GL (arui319)
Http://blog.csdn.net/arui319
<This article can be reproduced, but please keep the above author information. Thank you.>
---------------------------------------------------------------------------