在android中,當點擊一個按鈕顯示toast時,若連續點擊,那麼toast也會一直閃現,當停止點擊時還是在顯示,爲了防止這種情況出現,需要對其進行優化,若直接使用Toast.cancel()方法會不起作用,因此要自定義一個類,將其封裝、重寫。如下內容
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();
}
}
使用時,只需調用該類中的方法即可。雖然感覺邏輯合理,但還是在運行時還是會有bug出現,希望有誰解決掉了可以分享。
轉自:http://www.2cto.com/kf/201111/112527.html