在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
转载于:https://blog.51cto.com/9353753slq/1567121