Android中的倒计时器

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

        }
    }

}

它到底是怎么出问题的? - harism
启动后应用程序停止运行... onTick方法出现了一些问题... 如果将其注释掉,则应用程序可以正常工作... - tech_learner
3个回答

10

这一行代码导致了问题;

textView1.setText((int) (millisUntilFinished/1000));
你需要做的是为textView1设置一个资源id,而你寻找的可能是这样的东西;
textView1.setText(Long.toString(millisUntilFinished/1000));

同样是行;

        iFallApp app1 = new iFallApp();

这很可疑。为了避免意外使用它,请将其删除。你已经通过Android框架创建了你的iFallApp,如果需要,你可以使用this传递它。


1
提醒其他开发者,如果你将计时器抽象成自己的顶级类,请注意传递TextView给CountDownTimer实例会导致内存泄漏,如果不仔细清理引用,这将在旋转屏幕数次后变得明显,你的应用程序将像我的一样崩溃并显示OutOfMemoryError。请添加一个像这样的方法到你的CountDownTimer中,并在拥有Activity/Fragment的onDestroy()/onDestroyView()被调用时调用它。
public void safeCancel() {
   this.textView1 = null;
   super.cancel();
}

0
通常你可以查看 adb logcat 的输出来确定出了什么问题。
我想,textView1 变量可能没有被正确设置,因此为空。
另外,我会在onResume() 函数中启动倒计时器,而不是在onCreate() 函数中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接