美文网首页Android进阶之路Android开发
Android Toast 自定义显示时长

Android Toast 自定义显示时长

作者: lebronzhen | 来源:发表于2021-09-02 11:35 被阅读0次

Android Toast 只支持两种时间 LENGTH_SHORT 2 秒,LENGTH_LONG 3.5 秒,但是有场景需要自定义显示时长就会有问题,所以需要自定义实现,下边是自定义的类,通过定时器来实现长时间的显示。

/**
 * 功能描述:自定义toast显示时长
 */
public class CustomToast {
    private Toast mToast;
    private TimeCount timeCount;
    private String message;
    private int gravity;
    private Context mContext;
    private Handler mHandler = new Handler();
    private boolean canceled = true;

    public CustomToast(Context context, int gravity, String msg) {
        message = msg;
        mContext = context;
        this.gravity = gravity;
    }

    /**
     * 自定义时长、居中显示toast
     *
     * @param duration
     */
    public void show(int duration) {
        timeCount = new TimeCount(duration, 1000);
        if (canceled) {
            timeCount.start();
            canceled = false;
            showUntilCancel();
        }
    }

    /**
     * 隐藏toast
     */
    public void hide() {
        if (mToast != null) {
            mToast.cancel();
        }
        if (timeCount != null) {
            timeCount.cancel();
        }
        canceled = true;
    }

    private void showUntilCancel() {
        if (canceled) { //如果已经取消显示,就直接return
            return;
        }
        mToast = ToastUtil.getToast(mContext, message, Toast.LENGTH_LONG, gravity);
        mToast.setGravity(gravity, 0, 0);
        mToast.show();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                showUntilCancel();
            }
        }, 3500);
    }

    /**
     * 自定义计时器
     */
    private class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval); //millisInFuture总计时长,countDownInterval时间间隔(一般为1000ms)
        }

        @Override
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            hide();
        }
    }
}

初始化构造函数需要传入显示的消息和显示的位置(上 中 下),然后调用show方法,如果还没到时间想隐藏可以调用hide方法
调用方法如下:

if (customToast != null) customToast.hide();
customToast = new CustomToast(context, Gravity.BOTTOM, title);
customToast.show(duration);

时长可以任意传入,都可以按需求显示出来。

相关文章

网友评论

    本文标题:Android Toast 自定义显示时长

    本文链接:https://www.haomeiwen.com/subject/cwoxwltx.html