2011-05-07 36 views
4

我正在實現倒數計時器,但它並不適合我。以下是代碼。Android中的CountDownTimer

package FinalProj.com; 

import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.TextView; 
import android.os.CountDownTimer; 

public class iFallApp extends Activity{ 
    public TextView textView1; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     //TextView textview = new TextView(this); 
     //textview.setText("This is the iFall tab"); 
     // setContentView() 
     setContentView(R.layout.ifallapp); 

     textView1=(TextView) findViewById(R.id.textView1); 

     MyCount counter = new MyCount(5000,1000); 
     counter.start(); 


    } 

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

     iFallApp app1 = new iFallApp(); 

     @Override 
     public void onFinish() { 
      // TODO Auto-generated method stub 

      textView1.setText("done"); 
     } 

     @Override 
     public void onTick(long millisUntilFinished) { 
      // TODO Auto-generated method stub 

      textView1.setText((int) (millisUntilFinished/1000)); 

     } 
    } 

} 
+0

它究竟是如何行事不端? – harism 2011-05-07 22:14:31

+0

啓動應用程序後停止... onTick方法有一些問題...如果我註釋掉,那麼應用程序工作正常... – 2011-05-07 22:15:35

回答

10

這是導致問題的線路;

textView1.setText((int) (millisUntilFinished/1000)); 

你所做的是爲textView1設置一個資源ID,而你正在尋找的是類似的東西;

textView1.setText(Long.toString(millisUntilFinished/1000)); 

也行;

 iFallApp app1 = new iFallApp(); 

相當可疑。將其移除以防萬一您不小心使用它。您已經通過Android框架創建了您的iFallApp,如果需要,您可以使用this來傳遞它。

0

通常你應該能夠看adb logcat輸出,以確定什麼錯。

關閉我的頭頂我會說,textView1變量沒有正確設置,爲空。

此外,我會在onResume()函數中啓動倒數計時器,而不是onCreate()函數。

1

以此爲例,任何其他開發者都應該注意一下,但是已經將它們的Timer抽象爲它自己的頂級類。如果您不仔細清理引用,則將TextView傳遞到CountDownTimer實例將導致內存泄漏。在旋轉屏幕6次之後,這一點將會很明顯,你的應用程序會像我一樣會出現OutOfMemoryError。

像這樣向CountDownTimer添加一個方法,並在調用擁有Activity/Fragment的onDestroy()/ onDestroyView()時調用它。

public void safeCancel() { 
    this.textView1 = null; 
    super.cancel(); 
}