标签:
------你需要努力,你还没资格休息-----
Anroid中的倒计时实现:
在此先叙述小弟了解的,以后再补充整理。见谅
1、Timer和TimerTask
public class TimerTask extends Activity { //设置一个倒计时 private int recLen =12; private TextView textview; Timer timer=new Timer(); public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.timertask); textview=(TextView)findViewById(R.id.txttime); //延迟1000毫秒后再开始执行,第二个1000是间隔多长时间执行一次 timer.schedule(task,1000,1000); //timertask } TimerTask task=new TimerTask(){ public void run(){ //跳到主线程跟新 runOnUiThread(new Runnable(){//ui thread public void run(){ recLen --; textview.setText(""+recLen ); //判断倒计时是否走完 if(recLen<0){ //停止执行 timer.cancel(); //隐藏倒计时 textview.setVisibility(View.GONE); } } }); } } }
2、TimerTask与Handler(不用Timer的改进型)
public class TimerTask extends Activity { //设置一个倒计时 private int recLen =12; private TextView textview; Timer timer=new Timer(); public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.timertask); textview=(TextView)findViewById(R.id.txttime); //延迟1000毫秒后再开始执行,第二个1000是间隔多长时间执行一次 timer.schedule(task,1000,1000); //timertask } final Handler handler=new Handler(){ public void handleMessage(Message msg){ switch(msg.what){ case 1: textview.setText(""+recLen ); //判断倒计时是否走完 if(recLen<0){ //停止执行 timer.cancel(); //隐藏倒计时 textview.setVisibility(View.GONE); } } } } TimerTask task=new TimerTask(){ public void run(){ recLen--; //发送消息到handler中进行处理 Message message=new Message(); message.what=1; handler.sendMessage(message); } } }
}
----------小弟才艺不精,如有纰漏.请各位赐教------
标签:
原文地址:http://www.cnblogs.com/yangyiyi/p/5209457.html