倒計時(模擬短信驗證)、模仿活動倒計時

一、獲取短信倒計時

內容:介紹倒計時CountDownTimer的基本使用方法。模擬短信驗證

步驟:

1、繼承CountDownTimer,重寫onTick()、onFinish()

2、代碼中new出CountDownTimer子類,傳好參數,調用start()執行

代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.leixiansheng.countdowntimer.MainActivity">

    <TextView
        android:id="@+id/tv_getMsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="獲取短信驗證碼"
        android:background="@color/colorPrimaryDark"
        android:textSize="16sp"
        android:textColor="#ffffffff" />
</RelativeLayout>

 TimerCount

package com.example.leixiansheng.countdowntimer;

import android.os.CountDownTimer;
import android.widget.TextView;

/**
 * Created by Leixiansheng on 2018/7/18.
 */

public class TimerCount extends CountDownTimer {

	private TextView mTextView;


	public TimerCount(long millisInFuture, long countDownInterval, TextView textView) {
		super(millisInFuture, countDownInterval);
		mTextView = textView;
	}

	@Override
	public void onTick(long millisUntilFinished) {
		mTextView.setClickable(false);
		mTextView.setText("重新獲取" + millisUntilFinished / 1000 + "秒");
	}

	@Override
	public void onFinish() {
		mTextView.setClickable(true);
		mTextView.setText("獲取短信驗證碼");
	}
}

Main

package com.example.leixiansheng.countdowntimer;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		final TextView textView = (TextView) findViewById(R.id.tv_getMsg);
		textView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				/**
				 * millisInFuture:要計數的總時長
				 * countDownInterval:每隔多少秒響應
				 */
				TimerCount timerCount = new TimerCount(5000, 1000, textView);
				timerCount.start();
			}
		});
	}
}

 二、活動倒計時(計時時間長)

public class ActTimeCountDown extends AppCompatActivity {

    @BindView(R.id.time)
    TextView mTextView;
    @BindView(R.id.timerView)
    CountTimerView timerView;

    Handler handler = new Handler();
    private long leftTime = 60 * 60 * 24 * 100 + 5;        //剩餘時間

    private Handler handlerStop = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    leftTime = 0;
                    handler.removeCallbacks(update_thread);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private Runnable update_thread = new Runnable() {
        @Override
        public void run() {
            leftTime--;
            LogUtil.e("leftTime=" + leftTime);
            if (leftTime > 0) {
                //倒計時效果展示
                String formatLongToTimeStr = formatLongToTimeStr(leftTime);
                mTextView.setText(formatLongToTimeStr);
                //每一秒執行一次
                handler.postDelayed(this, 1000);
            } else {//倒計時結束
                //處理業務流程

                //發送消息,結束倒計時
                Message message = new Message();
                message.what = 1;
                handlerStop.sendMessage(message);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_time_count_down);
        ButterKnife.bind(this);

        //開始倒計時
        handler.postDelayed(update_thread, 1000);
    }

    public String formatLongToTimeStr(Long date) {
        long day = date / (60 * 60 * 24);
        long hour = (date / (60 * 60) - day * 24);
        long min = ((date / 60) - day * 24 * 60 - hour * 60);
        long s = (date - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        String strTime = "剩餘:" + day + "天" + hour + "小時" + min + "分" + s + "秒";
        return strTime;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        leftTime = 0;
        handler.removeCallbacks(update_thread);
    }
}

 三、活動倒計時(計時時間短)

自定義view進行封裝

public class CountTimerView extends LinearLayout {
    private TextView tvDayDecade;
    private TextView tvDayUnit;
    private TextView tvHourDecade;
    private TextView tvHourUnit;
    private TextView tvMinDecade;
    private TextView tvMinUnit;
    private TextView tvSecDecade;
    private TextView tvSecUnit;

    private TextView tvZero;
    private TextView tvOne;
    private TextView tvTwo;
    private TextView tvThree;

    private Context context;

    private long time;
    private MyCount mc;

    private int hour_decade;
    private int hour_unit;
    private int min_decade;
    private int min_unit;
    private int sec_decade;
    private int sec_unit;

    private int days_decade;
    private int days_unit;

    private stopListener listener;


    public void getStopListener(stopListener listener) {
        this.listener = listener;
    }

    public interface stopListener {
        void isStop();
    }


    public CountTimerView(Context context, AttributeSet attrs) {
        super(context, attrs);

        this.context = context;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.count_down_timer, this);
        tvDayDecade = (TextView) view.findViewById(R.id.tvDayDecade);
        tvDayUnit = (TextView) view.findViewById(R.id.tvDayUnit);
        tvHourDecade = (TextView) view.findViewById(R.id.tvHourDecade);
        tvHourUnit = (TextView) view.findViewById(R.id.tvHourUnit);
        tvMinDecade = (TextView) view.findViewById(R.id.tvMinDecade);
        tvMinUnit = (TextView) view.findViewById(R.id.tvMinUnit);
        tvSecDecade = (TextView) view.findViewById(R.id.tvSecDecade);
        tvSecUnit = (TextView) view.findViewById(R.id.tvSecUnit);
        tvZero = (TextView) view.findViewById(R.id.tvZero);
        tvOne = (TextView) view.findViewById(R.id.tvOne);
        tvTwo = (TextView) view.findViewById(R.id.tvTwo);
        tvThree = (TextView) view.findViewById(R.id.tvThree);
    }


    public void setTime(long ms) {
        time = ms / 1000;
        mc = new MyCount(time * 1000, 1000);
        mc.start();
    }


    private class MyCount extends CountDownTimer {


        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long l) {
            long ltime = l / 1000;
            int hour = (int) (ltime / (60 * 60));
            int minute = (int) ((ltime - hour * 60 * 60) / 60);
            int second = (int) (ltime - hour * 60 * 60 - minute * 60);

            hour_decade = hour / 10;
            hour_unit = hour % 10;

            min_decade = minute / 10;
            min_unit = minute % 10;

            sec_decade = second / 10;
            sec_unit = second % 10;

            if (ltime > 86400) {
                if (tvDayDecade.getVisibility() != VISIBLE) {
                    tvDayDecade.setVisibility(VISIBLE);
                    tvDayUnit.setVisibility(VISIBLE);
                    tvZero.setVisibility(VISIBLE);
                }

                int days = hour / 24;
                days_decade = days / 10;
                days_unit = days % 10;

                int hours = hour % 24;
                hour_decade = hours / 10;
                hour_unit = hours % 10;

                tvDayDecade.setText(days_decade + "");
                tvDayUnit.setText(days_unit + "");
                tvHourDecade.setText(hour_decade + "");
                tvHourUnit.setText(hour_unit + "");
                tvMinDecade.setText(min_decade + "");
                tvMinUnit.setText(min_unit + "");
                tvSecDecade.setText(sec_decade + "");
                tvSecUnit.setText(sec_unit + "");
            } else {
                if (tvDayDecade.getVisibility() != GONE) {
                    tvDayDecade.setVisibility(GONE);
                    tvDayUnit.setVisibility(GONE);
                    tvZero.setVisibility(GONE);
                }

                tvHourDecade.setText(hour_decade + "");
                tvHourUnit.setText(hour_unit + "");
                tvMinDecade.setText(min_decade + "");
                tvMinUnit.setText(min_unit + "");
                tvSecDecade.setText(sec_decade + "");
                tvSecUnit.setText(sec_unit + "");
            }
        }

        @Override
        public void onFinish() {
            mc.cancel();
            listener.isStop();
        }
    }
}

 佈局引入CountTimerView即可

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_time_count_down);
        ButterKnife.bind(this);

        timerView.setTime(1000 * (60 * 60 * 24 + 5));
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章