自定义Toast

来源:互联网 发布:nginx服务启动 编辑:程序博客网 时间:2024/06/06 09:57

修改原因:
1、防止多次点击Toast,在界面已经跳转但是Toast还在显示的bug;
2、区分正常与错误的状态,设置不同的背景色。

public class ToastManager {    private static Toast toast = null;//    private static Toast getToast(String msg){        if (toast==null){            synchronized (toast){                if (toast==null){                //该处的Context取自Application自定义方法                    Context context =SystemApplication.getContext();                    toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);                }            }        }else{            toast.setText(msg);        }        toast.setGravity(Gravity.BOTTOM, 0, 200);        return toast;    }    public static void showError(String msg) {        getToast(msg);        View view = toast.getView();        TextView tv = (TextView) view.findViewById(android.R.id.message);        view.setBackgroundColor(0xb0000000);        tv.setSingleLine(true);        tv.setTextColor(Color.parseColor("#FFFFFF"));        // tv.setTextSize();        toast.show();    }    public static void show(String msg) {        getToast(msg);        View view = toast.getView();        TextView tv = (TextView) view.findViewById(android.R.id.message);        tv.setGravity(Gravity.CENTER);        //view.setBackgroundColor(0xb0000000);        tv.setSingleLine(false);        tv.setTextColor(Color.parseColor("#FFFFFF"));//      tv.setTextColor(context.getResources().getColor(R.color.font_color));        // tv.setTextSize();        toast.show();    }    public void cancle() {        if (toast != null) {            toast.cancel();        }    }}

使用也非常简单:

ToastManager.showError("异常内容");

以上关于Toast设置单例模式,来自郭神的创意,为了形象生动,此处再借鉴两张效果图:

单例前:

这里写图片描述

单例后:

这里写图片描述

以上内容总结自大神demo及郭神创意,暂时无状态效果图。欢迎吐槽!

0 0
原创粉丝点击