packagecom.mytest.myclock;importjava.util.Timer;importjava.util.TimerTask;importandroid.app.AlertDialog;importandroid.content.Context;importandroid.os.Handler;importandroid.util.AttributeSet;importandroid.util.Log;importandroid.view.View;importandroid.widget.Button;importandroid.widget.LinearLayout;importandroid.widget.TextView;public class TimerView extendsLinearLayout {publicTimerView(Context context) {super(context);//TODO Auto-generated constructor stub

}public TimerView(Context context, AttributeSet attrs, intdefStyle) {super(context, attrs, defStyle);//TODO Auto-generated constructor stub

}publicTimerView(Context context, AttributeSet attrs) {super(context, attrs);//TODO Auto-generated constructor stub

}privateTextView tvHour;privateTextView tvMinute;privateTextView tvSecond;privateButton btnStart;privateButton btnStop;

@Overrideprotected voidonFinishInflate() {//TODO Auto-generated method stub

super.onFinishInflate();

init();

}private voidinit() {

tvHour= (TextView) this.findViewById(R.id.timer_hour);

tvMinute= (TextView) this.findViewById(R.id.timer_mini);

tvSecond= (TextView) this.findViewById(R.id.timer_second);

btnStart= (Button) this.findViewById(R.id.btn_start_timer);

btnStop= (Button) this.findViewById(R.id.btn_stop_timer);

btnStop.setOnClickListener(newView.OnClickListener() {

@Overridepublic voidonClick(View v) {

stopTimer();

}

});

btnStart.setOnClickListener(newView.OnClickListener() {

@Overridepublic voidonClick(View v) {

startTimer();

}

});

}private final int WORK_STATE_STOP = 0; //计时状态,停止

private final int WORK_STATE_RUN = 1;//计时状态

private int userInputTime = 0;privateTimer timer;privateTimerTask task;private Handler handler = newHandler() {public voidhandleMessage(android.os.Message msg) {switch(msg.what){caseWORK_STATE_RUN:int hour = userInputTime/60/60;int minute = (userInputTime/60)%60;int second = userInputTime%60;

tvHour.setText(""+hour);

tvMinute.setText(""+minute);

tvSecond.setText(""+second);break;caseWORK_STATE_STOP:new AlertDialog.Builder(getContext()).setTitle("时间到").setNegativeButton("取消", null).show();

stopTimer();break;

}

};

};private voidstartTimer() {try{

userInputTime= (Integer.parseInt(tvHour.getText().toString()) * 60 * 60

+ Integer.parseInt(tvMinute.getText().toString()) * 60

+Integer.parseInt(tvSecond.getText().toString()));

}catch(Exception e) {

Log.e("info", "TimerView->startTimer"+e.getMessage());return;

}

timer= newTimer();

task= newTimerTask() {

@Overridepublic voidrun() {

userInputTime--;

handler.sendEmptyMessage(WORK_STATE_RUN);if(userInputTime <=0){

handler.sendEmptyMessage(WORK_STATE_STOP);

stopTimer();

}

}

};

timer.schedule(task,1000,1000); //延迟一秒,再每隔一秒执行一次timertask.run()

}private voidstopTimer() {if(task!=null){

task.cancel();

task= null;

}

}

}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐