產品在測試過程中發現一個bug,就是測試人員不停的瘋狂的點擊某個按鈕,觸發了toast以后,toast內容會一直排著隊的顯示出來,不能很快的消失。這樣可能會影響用戶的使用。
看到Toast有一個cancel()方法:
void cancel()
Close the view if it's showing, or don't show it if it isn't showing yet.
做程序員的,基本一看api就知道,用這個可以取消上一個toast的顯示,然后顯示下一個,這樣就能解決出現的問題。可是在測試的過程中,發現卻沒有想象中的那么簡單,不信可以百度一下,很多很多人發現toast的cancel()方法不起作用。還是不講具體過程,只講結果吧。我把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 <A >http://VeVB.COm</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();
}
}
代碼的邏輯很簡單。這里加了同步,這樣做可以確保每一個toast的內容至少可以顯示出來,而不是還沒顯示就取消掉了。這樣做,是因為toast的內容不一定完全相同,如果沒顯示出來,也會有問題。