实际项目中,Toast显示默认为队列显示;致使app已经过了提示,还在提示造成体验不好。
以下解决:
public class ToastUtils {
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 context, 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.setText(msg);
toast.setDuration(len);
} else {
toast = Toast.makeText(context, msg, len);
}
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
});
}
}).start();
}
public static void showMessage(final Context context, final int msgId,
final int len) {
new Thread(new Runnable() {
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
synchronized (synObj) {
if (toast != null) {
toast.setText(msgId);
toast.setDuration(len);
} else {
toast = Toast.makeText(context, msgId, len);
}
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
});
}
}).start();
}
}