protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.other_main);
<span style="white-space:pre"> </span>//开始进行更新 selfHandler.postDelayed(runnable, 1000); findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selfHandler.removeCallbacks(runnable); } }); } Handler selfHandler = new Handler(); Runnable runnable = new Runnable() { @Override public void run() { try { selfHandler.postDelayed(this,1000); swit.setText(String.valueOf(new Date())); }catch (Exception e){ System.out.println("exception " + e); } } };
1.定时器实现步骤:
1. 创建Handler对象。注意是
import android.os.Handler,下的handler.
2. 创建runnable对象
Runnable runnable = new Runnable() { @Override public void run() { try { // selfHandler.postDelayed(this,1000); swit.setText(String.valueOf(new Date())); //需要执行的语句。swit是一个textSwitcher }catch (Exception e){ System.out.println("exception " + e); } } };附带 : swit之TextSwitcher代码
swit = (TextSwitcher) findViewById(R.id.textSwitcher); swit.setFactory(this); Animation in = AnimationUtils.loadAnimation(this, android.R.anim.fade_in); Animation out = AnimationUtils.loadAnimation(this, android.R.anim.fade_out); swit.setInAnimation(in); swit.setOutAnimation(out);
3.在Oncreate方法中,进行调用
selfHandler.postDelayed(runnable, 1000);4.我添加了一个按钮,可以停止这个定时器
findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selfHandler.removeCallbacks(runnable); //Handler,Runnable与上面对应 } });
总结:
我是用Android studio创建的项目:
下载代码:源码下载