一、优化原因
主要是多次申请同一个Toast,会多次弹出。其实我只要他弹出一次,只有这个Toast销毁了我才需要下一个。
二、优化后代码
import android.content.Context;
import android.widget.Toast;
public class ToastUtil {
private static String oldMsg;
protected static Toast toast = null;
private static long oneTime = 0;
private static long twoTime = 0;
public static void showToast(Context context, String s) {
if (toast == null) {
toast = Toast.makeText(context, s, Toast.LENGTH_SHORT);
toast.show();
oneTime = System.currentTimeMillis();
} else {
twoTime = System.currentTimeMillis();
if (s.equals(oldMsg)) {
if (twoTime - oneTime > Toast.LENGTH_SHORT) {
toast.show();
}
} else {
oldMsg = s;
toast.setText(s);
toast.show();
}
}
oneTime = twoTime;
}
public static void showToast(Context context, int resId) {
showToast(context, context.getString(resId));
}
}