2024年3月11日发(作者:)

Android自定义Toast,多次弹出时取消上次弹出,最后一次弹出为准

Android的Toast用队列管理弹出的消息,这个自定义的Toast用于频繁弹出Toast时取消之

前的toast,只显示最后一个Toast,前后文字长度相差较大时,两个Toast提示的切换不太

理想,大神们有啥建议还望不吝赐教。

public abstract class Toast {

public static final int LENGTH_SHORT = _SHORT;

public static final int LENGTH_LONG = _LONG;

private static toast;

private static Handler handler = new Handler();

private static Runnable run = new Runnable() {

public void run() {

();

private static void toast(Context ctx, CharSequence msg, int duration) {

Callbacks(run);

// handler的duration不能直接对应Toast的常量时长,在此针对Toast的常量相应定义时

switch (duration) {

case LENGTH_SHORT:// _SHORT值为0,对应的持续时间大概为1s

duration = 1000;

break;

case LENGTH_LONG:// _LONG值为1,对应的持续时间大概为3s

duration = 3000;

break;

default:

break;

if (null != toast) {

t(msg);

} else {

toast = xt(ctx, msg, duration);

layed(run, duration);

();

* 弹出Toast

* @param ctx

* 弹出Toast的上下文

* @param msg

* 弹出Toast的内容

* @param duration

* 弹出Toast的持续时间

public static void show(Context ctx, CharSequence msg, int duration)

throws NullPointerException {

if (null == ctx) {

throw new NullPointerException( The ctx is null!

if (0 duration) {

duration = LENGTH_SHORT;

toast(ctx, msg, duration);

* 弹出Toast

* @param ctx

* 弹出Toast的上下文

* @param msg

* 弹出Toast的内容的资源ID

* @param duration

* 弹出Toast的持续时间

public static void show(Context ctx, int resId, int duration)

throws NullPointerException {

if (null == ctx) {

throw new NullPointerException( The ctx is null!

if (0 duration) {

duration = LENGTH_SHORT;

toast(ctx, ources().getString(resId), duration);