产品在测试过程中发现一个bug,就是测试人员不停的疯狂的点击某个按钮,触发了toast以后,toast内容会一直排着队的显示出来,不能很快的消失。这样可能会影响用户的使用。
看到Toast有一个cancel()方法:
<nobr>void</nobr> | <nobr><span class="sympad" style="margin-right:2px"><a href="file:///D:/Program%20Files/Android/android-sdk/docs/reference/android/widget/Toast.html#cancel()" style="color:rgb(0,102,153); text-decoration:none">cancel</a></span>()</nobr>
Close the view if it's showing, or don't show it if it isn't showing yet.
|
我把toast做成了一个应用类,方便使用,大家可以直接用:
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() { @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(); } }
代码的逻辑很简单。这里加了同步,这样做可以确保每一个toast的内容至少可以显示出来,而不是还没显示就取消掉了。这样做,是因为toast的内容不一定完全相同,如果没显示出来,也会有问题。
---------------------------------------------------------------------------
GL(arui319)
http://blog.csdn.net/arui319
<本文可以转载,但是请保留以上作者信息。谢谢。>
---------------------------------------------------------------------------