本文共 2478 字,大约阅读时间需要 8 分钟。
好吧……我承认很尴尬……
但毕竟作为开端,还是将这个贴出来,以后一定写出厉害的!
package myapplication.nomasp.com.timer;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import java.util.Timer;import java.util.TimerTask;public class MainActivity extends Activity implements View.OnClickListener { private EditText etInputNum,etOutputNum; private Button btnGetNum,btnStartCount,btnStopCount; private TextView tvOutputNum; private int i=0; private Timer timer=null; private TimerTask task=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView(){ etInputNum=(EditText)findViewById(R.id.etInputNum); btnGetNum=(Button)findViewById(R.id.btnGetNum); btnStartCount=(Button)findViewById(R.id.btnStartCount); btnStopCount=(Button)findViewById(R.id.btnStopCount); tvOutputNum=(TextView)findViewById(R.id.tvOutputNum); btnGetNum.setOnClickListener(this); btnStartCount.setOnClickListener(this); btnStopCount.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnGetNum: tvOutputNum.setText(etInputNum.getText().toString()); i=Integer.parseInt(etInputNum.getText().toString()); break; case R.id.btnStartCount: startTime(); break; case R.id.btnStopCount: stopTime(); break; default: break; } } private Handler mHandler=new Handler(){ public void handleMessage(Message msg){ tvOutputNum.setText(msg.arg1+""); startTime(); }; }; public void startTime(){ timer=new Timer(); task =new TimerTask() { @Override public void run() { i--; Message message=mHandler.obtainMessage(); message.arg1=i; mHandler.sendMessage(message); } }; timer.schedule(task,1000); } public void stopTime(){ timer.cancel(); }}
加油!
转载地址:http://eabsx.baihongyu.com/