4

我正在实现倒数计时器,但它对我不起作用。下面是代码。

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));

        }
    }

}
4

3 回答 3

10

是这条线导致了问题;

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

您所做的是为 textView1 设置资源 ID,而您正在寻找的是类似的东西;

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

也行;

        iFallApp app1 = new iFallApp();

比较可疑。以防万一在您最终意外使用它之前将其删除。您已经拥有由 Android 框架创建的 iFallApp,this如果需要,您可以使用它来代替。

于 2011-05-07T22:25:48.663 回答
1

以此为例,请注意任何其他开发人员,但已将他们的 Timer 抽象为自己的顶级类。如果不仔细清理引用,将 TextView 传递到 CountDownTimer 实例将导致内存泄漏。这在屏幕旋转六次后会很明显,你的应用程序会像我的一样因 OutOfMemoryError 而崩溃。

像这样向您的 CountDownTimer 添加一个方法,并在调用拥有的 Activity/Fragment 中的 onDestroy()/onDestroyView() 时调用它。

public void safeCancel() {
   this.textView1 = null;
   super.cancel();
}
于 2013-03-31T22:25:37.837 回答
0

通常,您应该能够查看adb logcat输出以确定出了什么问题。

在我的脑海中,我会说该textView1变量没有正确设置并且为空。

另外,我会在函数中启动倒数计时器onResume(),而不是onCreate()函数。

于 2011-05-07T22:22:10.217 回答