写点什么

ToastUtil 实用封装

用户头像
Changing Lin
关注
发布于: 刚刚
ToastUtil实用封装

1.Toast

A toast is a view containing a quick little message for the user. The toast class helps you create and show those.

When the view is shown to the user, appears as a floating view over the application. It will never receive focus. The user will probably be in the middle of typing something else. The idea is to be as unobtrusive as possible, while still showing the user the information you want them to see. Two examples are the volume control, and the brief message saying that your settings have been saved.

The easiest way to use this class is to call one of the static methods that constructs everything you need and returns a new Toast object.

简单来讲,Toast 是一个控件,用来为用户展示快速简短信息。它是以悬浮在应用上的方式显示,无法获取焦点。两个简单的例子是,音量控制和简单告诉用户设置已经保存。一般的使用方法是,用 Toast 里面的静态方法来构造。为了实现项目需求、避免重复提示的情况,提升用户体验,有必要进行二次封装。

2.代码

  • Timeout 类:用于实现计时功能

import android.text.TextUtils;
public class Timeout{ //限制网络异常提示的间隔,4秒内只允许提示1次 private static final long IntervalShowError = 4000;//两次弹窗的最小间隔时间 private String msg; private int resId; private long time;
public boolean exist(String msg){ return TextUtils.equals(this.msg, msg); }
public boolean exist(int resId){ return this.resId == resId; }
public void cache(String msg){ this.msg = msg; this.time = System.currentTimeMillis(); }
public void cache(int resId){ this.resId = resId; this.time = System.currentTimeMillis(); }
public boolean isDuplicated(){ return System.currentTimeMillis() - time < IntervalShowError; }}
复制代码
  • ToastUtil 类:吐司操作调用工具类

import android.content.Context;import android.text.TextUtils;import android.util.Log;import android.widget.Toast;
public class ToastUtil { private static final Timeout timeout = new Timeout();
public static void showToast(Context context, String message) { if (context == null) { return; } if (timeout.exist(message) && timeout.isDuplicated()){ return; } timeout.cache(message); Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); }
public static void showToast(Context context, int resId) { showToast(context, resId, true); }
public static void showToast(Context context, int resId, boolean isDuplicateCheck) { if (context == null) { return; } if (isDuplicateCheck) { if (timeout.exist(resId) && timeout.isDuplicated()) { return; } timeout.cache(resId); } Toast.makeText(context, context.getString(resId), Toast.LENGTH_SHORT).show(); }}
复制代码

3.总结

通过几个文件的封装,简化使用 API,实现避免重复提示(同一内容 4 秒内只允许提示 1 次)的情况,提升用户体验,有必要进行二次封装。

发布于: 刚刚阅读数: 2
用户头像

Changing Lin

关注

获得机遇的手段远超于固有常规之上~ 2020.04.29 加入

我能做的,就是调整好自己的精神状态,以最佳的面貌去面对那些未曾经历过得事情,对生活充满热情和希望。

评论

发布
暂无评论
ToastUtil实用封装