實現android專案標題每隔5秒改變一次
阿新 • • 發佈:2019-02-14
package com.example.titleclockproject; import java.util.Timer; import java.util.TimerTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.view.Menu; import android.view.MenuItem; import android.support.v4.app.NavUtils; public class MainActivity extends Activity { private int count=1; private Handler handler=new Handler(){ public void handleMessage(android.os.Message msg) { switch (msg.what) { case 1: updateTitle(); break; default: break; } }; }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //第一種方法(1秒之後開始,間隔5秒) Timer timer=new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { Message message=new Message(); message.what=1; handler.sendMessage(message); } }, 1000,5000); //第二種方法 //TitleChange titleChange=new TitleChange(); //Thread thread=new Thread(titleChange); //thread.start(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } // class TitleChange implements Runnable{ // // @Override // public void run() { // while(true){ // Message message=new Message(); // message.what=1; // handler.sendMessage(message); // try { // Thread.sleep(5000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // } // // } private void updateTitle(){ this.setTitle("welcome to project"+count++); } }