Android之LongTimeToast

来源:互联网 发布:星空倒影 知乎 编辑:程序博客网 时间:2024/06/09 17:29

今天需要处理一个给用户的提示,Toast就可以,但是显示的时间不符合要求,太短

大概看了一眼Toast的源码,发现问题大概在show()里一开始的想法,新建一个类继承Toast,然并卵,出错啦

// Caused by: java.lang.ClassCastException: android.widget.Toast cannot be cast to com.cl.slack.toast.LongTimeToast
// LongTimeToast extends Toast
LongTimeToast l = ((LongTimeToast)Toast.makeText(this,"111111111111",Toast.LENGTH_LONG));
l.setDuring(10000).show();

换个思路,实现挺简单的,直接上代码


import android.content.Context;import android.os.CountDownTimer;import android.support.annotation.StringRes;import android.widget.Toast;/** * 自定义显示toast显示时间 * Created by slack on 2016/11/25. */public class LongTimeToast{    private static int mDuration = 2000;// 单位 毫秒 ms    private boolean mShowing = false;    private Toast mToast;    private String message;//test    public LongTimeToast(Context context,String msg ,int duration) {        mToast = Toast.makeText(context,msg,Toast.LENGTH_SHORT);        mDuration = duration;        message = msg;    }    public LongTimeToast(Context context, @StringRes int resId, int duration) {        new LongTimeToast(context,context.getResources().getString(resId),duration);    }    // 这里是一直调用 mToast.show();    public void show() {        if (mShowing) return;        mToast.show();        mShowing = true;        new CountDownTimer(mDuration, 200) {            public void onTick(long millisUntilFinished) {                mToast.setText(message + millisUntilFinished);                mToast.show();            }            public void onFinish() {                mToast.cancel();                mShowing = false;            }        }.start();    }}

使用:
new LongTimeToast(this,"this is test,time left ",5000).show();

0 0