public final int MSG_WHART=10; private int count=10; private TextView start,timer; Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch(msg.what){ case MSG_WHART: if (count<0){ stopTimer(); }else { timer.setText(count+""); count--; handler.sendEmptyMessageDelayed(MSG_WHART,1000); } break; } } };
private void startTimer() { if (count<=0){ count=10; handler.sendEmptyMessage(MSG_WHART); start.setText("开始"); }else { handler.sendEmptyMessage(MSG_WHART); start.setText("暂停"); } } private void stopTimer() { handler.removeMessages(MSG_WHART); start.setText("开始"); }
start= (TextView) findViewById(R.id.start); timer= (TextView) findViewById(R.id.timer); start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (start.getText().toString().equals("暂停")){ handler.removeMessages(MSG_WHART); start.setText("开始"); }else { startTimer(); } } });