2013-12-22 156 views
0

我已經爲Android編寫了一個倒計時應用,到目前爲止,我已經設法從應用打開時開始顯示時間,但不會刷新。我認爲這與使用postDelayed函數有關,但我不知道如何應用此功能,而且我無法從文檔中找出任何內容。幫助將大量讚賞!每秒重複一次腳本

我到目前爲止有:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Time now = new Time(); 
    now.setToNow(); 

    Time decision = new Time(); 
    decision.set(7, 0, 2014); 

    long nowutc = now.toMillis(false); 
    long decutc = decision.toMillis(false); 

    long difference = decutc - nowutc; 

    int days = (int) difference/86400000; 
    int hours = (int) (difference % 86400000)/3600000; 
    int leftover = (days*86400000) + (hours*3600000); 
    int minutes = (int) (difference - leftover)/60000; 
    int secleft = (int) leftover + (minutes*60000); 
    int seconds = (int) (difference-secleft)/1000; 

    ((TextView)findViewById(R.id.time)).setText(days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds "); 
    } 
+0

您可以通過刷新是什麼意思?如果您將應用程序發送到後臺或者您期望的是什麼,您是否應該重置時間? – Prem

+0

看看這個鏈接http://stackoverflow.com/questions/4873196/dynamically-update-textview-in-android –

+0

我的意思是腳本每秒運行一次,所以計時器實際上倒數而不是保持靜態。 – CuriousCabbage

回答

0

試試這個:

private int mInterval = 500; // ms 
private Handler mHandler; 
private TextView mTextView; 

@Override 
protected void onCreate(Bundle bundle) { 
    setContentView(R.layout.whatever); 
    mTexView = (TextView) findViewById(R.id.time); 
    mHandler = new Handler(); 
    mHandler.post(mUpdateTime); 
} 

Runnable mUpdateTime = new Runnable() { 
    @Override 
    public void run() { 
     Time now = new Time(); 
     now.setToNow(); 

     Time decision = new Time(); 
     decision.set(7, 0, 2014); 

     long nowutc = now.toMillis(false); 
     long decutc = decision.toMillis(false); 

     long difference = decutc - nowutc; 

     int days = (int) difference/86400000; 
     int hours = (int) (difference % 86400000)/3600000; 
     int leftover = (days*86400000) + (hours*3600000); 
     int minutes = (int) (difference - leftover)/60000; 
     int secleft = (int) leftover + (minutes*60000); 
     int seconds = (int) (difference-secleft)/1000; 
     mTextView.setText(days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds "); 
     mHandler.postDelayed(mUpdateTime, mInterval); 
    } 
}; 
+0

完美的作品,非常感謝你! – CuriousCabbage