2012-04-04 142 views
10

我想在android中寫一個從3開始計數到0的倒數計時器。先出現3個然後消失和2個出現等等。我搜查了很多,但我找不到任何好的樣本。你能幫我嗎?我該怎麼辦?Android倒數計時器

+0

使用的AsyncTask :) – pgsandstrom 2012-04-04 12:04:30

+0

檢查這一點 - https://stackoverflow.com/a/47695735/ 6244429 – 2017-12-07 13:42:47

回答

18

使用CountDownTimer

例如:

import android.os.CountDownTimer; 

MyCount timerCount; 
public class TestCountdown extends Activity { 

    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    timerCount = new MyCount(3 * 1000, 1000); 
    timerCount.start(); 
    } 

    public class MyCount extends CountDownTimer { 
     public MyCount(long millisInFuture, long countDownInterval) { 
     super(millisInFuture, countDownInterval); 
     } 

     @Override 
     public void onFinish() { 
     //some script here 
     } 

     @Override 
     public void onTick(long millisUntilFinished) { 
     //some script here 
     } 
    } 
} 
0

我不會寫這個代碼,但這應該不難。只需使用一個線程來顯示值3(使用說TextView)然後睡覺說(假設你希望它改變100毫秒後1秒),然後減少並重復。

一個例子是

for i=0 to 3 
print the number 
thread.sleep(100)