定期更新Android TextView以显示倒计时

Ric*_*ich 5 android android-widget

我试图CountDownTimer在Android中使用TextView从100到零的倒计时.我希望尽快发生,同时保持可见.

目前,如果CountDownTimer滴答间隔小于500毫秒(我认为就是这样,可能会低一点),那么更新就不会发生.

我只在模拟器上试过这个.

我是否以正确的方式解决这个问题?如果我是,这种明显的缓慢是模拟器的限制还是我必须忍受的东西?如果这不是正确的方法,有人可以推荐一种不同的方法吗?

chi*_*jib 11

请在模拟器和设备上检查以下示例代码

package com.sample;

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

public class SampleTimer extends Activity {

    TextView tv; // textview to display the countdown

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tv = new TextView(this);
        this.setContentView(tv);

         // 10000 is the starting number (in milliseconds)
        // 1000 is the number to count down each time (in milliseconds)

        MyCount counter = new MyCount(10000, 1000);
        counter.start();
    }


    // countdowntimer is an abstract class, so extend it and fill in methods
    public class MyCount extends CountDownTimer {

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

        @Override
        public void onFinish() {
            tv.setText("done!");
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tv.setText("Left: " + millisUntilFinished / 1000);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)