Android小项目之倒计时工具的实现

来源:互联网 发布:橱柜哪个牌子好 知乎 编辑:程序博客网 时间:2024/06/18 09:54

Android小项目之倒计时工具的实现的确很简单实现的方法

  • 使用Handler发送Message不带参数的延时空消息的方法
  • 使用继承自TimerTask类重写run方法,通过Handler更新UI界面

但需要注意的有以下几点

  1. 防止用户多次点击开始计时按钮导致创建多个计时器
  2. 要实现暂停效果,如何达成
  3. 防止用户输入小于等于0的不合法数字,直接抛出一个自定义的异常,并在catch中使用Toast进行提示(可以在EditText中对输入的内容限定为0~9)
  4. 当计时完毕后直接点击开始计时按钮即可开始下一轮计时
  5. 退出Activity时需要释放资源,否则会出现错误

这里写图片描述

package com.example.counttime;import java.util.Timer;import java.util.TimerTask;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity implements OnClickListener {    private static final String TAG = "MainActivity";    private Button mStartTime;    private Button mStopTime;    private Button mGetTime;    private TextView mTime;    private EditText mInputTime;    private int secondTime;    private MyTimerTask myTask;    private boolean isShouldBeNextTime = false;// 可以开始下次倒计时了    private boolean isPause = false;// 可以开始下次倒计时了    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initView();// 初始化控件    }    @Override    public void onClick(View v) {        switch (v.getId()) {        case R.id.btn_starttime:// 开始倒计时            if (myTask != null) {                // 防止用户多次点击开始计时按钮导致创建多个计时器                return;            }            getTime(isPause);            isPause = false;            if (secondTime > 0) {                // 当前计时还没有结束的情况下继续计时                startTime();            } else if (isShouldBeNextTime == true) {                // 已经进行了一轮计时,获取当前设置的时间进行下一轮计时                onClick(v);            }            break;        case R.id.btn_stoptime:// 停止倒计时            if (myTask != null) {// 防止用户在没有创建计时器的情况下就点击了该按钮                stopTime();                getTime(isPause);                isPause = true;            }            break;        case R.id.btn_gettime:// 重新计时            getTime(isPause);            isPause = false;            break;        default:            break;        }    }    private void getTime(boolean isPause) {        String time = "0";        try {            if (isPause == true) {// 判断是否是暂停的时候点击开始计时按钮如果是则                time = mTime.getText().toString().trim();            } else {                time = mInputTime.getText().toString().trim();            }            if (time.equals("0")) {                // 假如用户输入为0,则抛出自定义的异常;->为什么不用digits的原因是如果限定不能输入零,则无法输入整数                throw new inputEqualsZero("时间不能为0!");            } else if (Integer.parseInt(time) < 10) {                mTime.setText("0" + time);            }            secondTime = Integer.parseInt(time);        } catch (Exception e) {            Toast.makeText(MainActivity.this, e.getMessage(),                    Toast.LENGTH_SHORT).show();            e.printStackTrace();        }    }    private void stopTime() {        myTask.cancel();        myTask = null;// 把myTask赋值为null;    }    private void startTime() {        myTask = new MyTimerTask();        new Timer().schedule(myTask, 1000);// 只要没有调用task.cancel方法,Timer对象就会一直执行    }    class MyTimerTask extends TimerTask {        @Override        public void run() {            secondTime--;            Message msg = Message.obtain();// 通过Handler更新UI界面            msg.arg1 = secondTime;            handler.sendMessage(msg);        }    }    Handler handler = new Handler() {        @Override        public void handleMessage(Message msg) {            if (msg.arg1 < 10) {                mTime.setText("0" + msg.arg1);            } else {                mTime.setText("" + msg.arg1);// ;如果不是字符串会导致参数是R.id            }            if (secondTime <= 0) {// 如果时间为0则停止                stopTime();                isShouldBeNextTime = true;            } else {                startTime();// 这里切莫忘记了            }        }    };    class inputEqualsZero extends Exception {// 自定义的异常:如果输入的是0则则会抛出这个异常        public inputEqualsZero(String msg) {            super(msg);        }    }    private void initView() {        mStartTime = (Button) findViewById(R.id.btn_starttime);        mStopTime = (Button) findViewById(R.id.btn_stoptime);        mGetTime = (Button) findViewById(R.id.btn_gettime);        mTime = (TextView) findViewById(R.id.tv_time);        mInputTime = (EditText) findViewById(R.id.et_inputtime);        mStartTime.setOnClickListener(this);        mStopTime.setOnClickListener(this);        mGetTime.setOnClickListener(this);    }    @Override    protected void onDestroy() {        if (myTask != null) {            stopTime();        }        super.onDestroy();    }}

Activity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.example.counttime.MainActivity" >    <EditText        android:id="@+id/et_inputtime"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center"        android:hint="请输入倒计时"        android:inputType="number"        android:textSize="30sp" />    <Button        android:id="@+id/btn_gettime"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="重新计时" />    <Button        android:id="@+id/btn_starttime"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="开始计时" />    <Button        android:id="@+id/btn_stoptime"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="停止计时" />    <TextView        android:id="@+id/tv_time"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:gravity="center"        android:textSize="40sp" /></LinearLayout>
0 0
原创粉丝点击