可能是最好用的弹出Toast工具类
/**
* - Created by Luke on 2017/2/10.
*/
public class ToastUtil {
private static volatile ToastUtil sToastUtil = null;
private Toast mToast = null;
/**
* 获取实例
*
* @return ToastUtil
*/
public static ToastUtil getInstance() {
if (sToastUtil == null) {
synchronized (ToastUtil.class) {
if (sToastUtil == null) {
sToastUtil = new ToastUtil();
}
}
}
return sToastUtil;
}
protected Handler handler = new Handler(Looper.getMainLooper());
/**
* 显示Toast,多次调用此函数时,Toast显示的时间不会累计,并且显示内容为最后一次调用时传入的内容
* 持续时间默认为short
*
* @param tips 要显示的内容
* {@link Toast#LENGTH_LONG}
*/
public void show(final String tips) {
show(tips, Toast.LENGTH_SHORT);
}
public void show(final int tips) {
show(tips, Toast.LENGTH_SHORT);
}
/**
* 显示Toast,多次调用此函数时,Toast显示的时间不会累计,并且显示内容为最后一次调用时传入的内容
*
* @param tips 要显示的内容
* @param duration 持续时间,参见{@link Toast#LENGTH_SHORT}和
* {@link Toast#LENGTH_LONG}
*/
public void show(final String tips, final int duration) {
if (android.text.TextUtils.isEmpty(tips)) {
return;
}
handler.post(() -> {
if (mToast == null) {
mToast = Toast.makeText(MyApplication.getInstance(), tips, duration);
mToast.show();
} else {
mToast.setText(tips);
mToast.setDuration(duration);
mToast.show();
}
});
}
public void show(final int tips, final int duration) {
handler.post(() -> {
if (mToast == null) {
mToast = Toast.makeText(MyApplication.getInstance(), tips, duration);
mToast.show();
} else {
mToast.setText(tips);
mToast.setDuration(duration);
mToast.show();
}
});
}
}