自定义的可控制显示时长的Toast

/**
* 作者 : fy on 2015/10/19.
* 注释 :自定义可随意显示时长的Toast
*/

public class MyToast {

    Toast taost = null;
    Context mContext;
    String str;
    int i;
    private long firstTime;
    private Timer timer;

    /** * * @param context * @param str 要显示的内容 * @param i 要显示的时长 */
    public MyToast(Context context, String str, int i) {
        this.mContext = context;
        this.str = str;
        this.i = i;
    }

    MyTimerTask timerTask;

    public void showToast() {

        firstTime = System.currentTimeMillis();
        timerTask = new MyTimerTask();
        timer = new Timer(true);
        timer.schedule(timerTask, 0, 2000);//定时每秒执行一次
    }

    //定时任务,定时发送message
    private class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            Message message = Message.obtain();
            message.what = 1;

            if (System.currentTimeMillis() - firstTime < i) {
                System.out.println("----------" + (System.currentTimeMillis() - firstTime));
                mHandler.sendMessage(message);  //发送message
            } else {
                timer.cancel();
                System.out.println("quxiao toast");

                return;
            }

        }
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.what == 1) {
                if (taost != null) {
                    taost.cancel();
                    taost.makeText(mContext, str, Toast.LENGTH_LONG).show();
                }
                taost.makeText(mContext, str, Toast.LENGTH_LONG).show();
            }

        }
    };
}

你可能感兴趣的:(自定义可随意显示时长)