2011-05-07 65 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(); 
}