项目中封装的自定义Toast

来源:互联网 发布:wpf 实时显示数据 编辑:程序博客网 时间:2024/06/16 00:49

Android中经常用到Toast提示,项目中很多Toast提示,简单的封装一下,将Toast方法提出来,方便日常开发使用:


1.首先,封装自定义Toast(在开发中Xxx,可以使用项目名代替)

public class XxxToast {    private static String oldMsg = "";    protected static Toast toast = null;    private static long oneTime = 0;    private static long twoTime = 0;    public static final int LENGTH_LONG = 1;    public static final int LENGTH_SHORT = 0;    /**     * @param @param context 上下文     * @param @param s 要显示的字符串     * @param @param duration 要显示的时长,值为:LENGTH_LONG或LENGTH_SHORT     * @return void     * @throws     * @Title: showToast     * @Description: 根据传入的字符串显示toast     */    public static void showToast(Context context, String s, int duration) {        try {            if (toast == null) {                toast = Toast.makeText(context, s, duration);                toast.show();                oneTime = System.currentTimeMillis();            } else {                twoTime = System.currentTimeMillis();                if (s.equals(oldMsg)) {                    if (twoTime - oneTime > duration) {                        toast.show();                    }                } else {                    oldMsg = s;                    toast.setText(s);                    toast.show();                }            }            oneTime = twoTime;        } catch (RuntimeException e) {            e.getMessage();        }    }    /**     * @param @param context 上下文     * @param @param resId 资源id     * @param @param duration 要显示的时长,值为:LENGTH_LONG或LENGTH_SHORT     * @return void 返回类型     * @throws     * @Title: showToast     * @Description: 根据配置的字符串资源id显示toast     */    public static void showToast(Context context, int resId, int duration) {        showToast(context, context.getString(resId), duration);    }}
2.其次,就是如何调用

XxxToast.showToast(this, "需要吐司的内容", XxxToast.LENGTH_LONG);


1 0