private static Toast toast = null; public static Toast makeText(Context context, CharSequence text, int duration) { WeakReference<Context> mContext = new WeakReference<>(context); // 获取LayoutInflater对象 LayoutInflater inflater = (LayoutInflater) mContext.get() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // 由layout文件创建一个View对象 View layout = inflater.inflate(R.layout.view_toast, null); // 实例化ImageView和TextView对象 TextView textView = layout.findViewById(R.id.message); if (toast == null) { toast= new Toast(mContext.get()); textView.setText(text); toast.setView(layout); toast.setDuration(duration); }else{ textView.setText(text); toast.setView(layout); toast.setDuration(duration); } return toast; }R.layout.view_toast是一个自定义的layout,R.id.message是里面的文本,用于显示Toast信息,需要用带图片Toast的,请在R.layout.view_toast里自行添加ImageView
使用方法:和系统Toast一样~
下面的链接是单例模式实现的
http://www.jianshu.com/p/6e4dbfde8dd8
自定义Toast并只显示最后一次
最新推荐文章于 2021-05-28 10:20:39 发布