我们的app如果一个地方出现多次Toast, 一般的写法都是new的形式,这样会使toast弹出很多个! 下面方式是以覆盖的形式
直接上代码:
class SingleToast {
private static Toast mToast;
/**
* 双重锁定,使用同一个Toast实例
*/
public static Toast getInstance(Context context) {
if (mToast == null) {
synchronized (SingleToast.class) {
if (mToast == null) {
mToast = new Toast(context);
}
}
}
return mToast;
}
}
下面是自定义Toast使用的方法
/**
* 自定义中间吐司
*
* @param context context
* @param text 信息
*/
public static void showCenterToast(Context context, String text) {
if (!StrUtil.isEmpty(text)) {
View view = LayoutInflater.from(context).inflate(R.layout.toast_view, null);
TextView infoView = (TextView) view.findViewById(R.id.view_Toast_text);
infoView.setText(text);
Toast toast = SingleToast.getInstance(context.getApplicationContext());
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(view);
toast.show();
}
}