自定义的Toast

来源:互联网 发布:淘宝店铺复制危险吗 编辑:程序博客网 时间:2024/06/04 19:47

延迟显示Toast

private int showToastCount;private boolean toastFlag;private long showToastBegin, showToastEnd;/** * 延迟显示Toast * @param context 使用的上下文对象  * @param text 要显示的文本 * @param duration 要消息显示多长时间(可以取 Toast.LENGTH_LONG 或 Toast.LENGTH_SHORT) * @param count 一定时间段里的显示上限次数 * @param delay 多少秒内不显示Toast */private void limitShowToast(Context context, String text, int duration, int count, int delay) {    if (toastFlag) {        showToastEnd = System.currentTimeMillis();        if ((showToastEnd / 1000 - showToastBegin / 1000) > delay) {            toastFlag = false;            showToastCount = 0;        }    } else {        if (count > showToastCount) {            Toast.makeText(context, text, duration).show();            showToastCount++;        } else {            toastFlag = true;            showToastBegin = System.currentTimeMillis();        }    }}

使用方法:
limitShowToast(MainActivity.this, “测试文字”, Toast.LENGTH_SHORT, 2, 10);

控制Toast的显示时长

/** * 控制Toast的显示时长 * @param toast 要显示的 Toast * @param count 要显示的时长(单位:秒) */private void showToast(final Toast toast, int count) {    final Timer timer = new Timer();    timer.schedule(new TimerTask() {        @Override        public void run() {            toast.show();        }    }, 0, 2000);    new Timer().schedule(new TimerTask() {        @Override        public void run() {            toast.cancel();            timer.cancel();        }    }, count * 1000);}

使用方法:
Toast toast = Toast.makeText(MainActivity.this, “测试文字”, Toast.LENGTH_SHORT);
showToast(toast, 8);
注意不要在实例化 Toast 的时候添加“.show()”。

0 0
原创粉丝点击