如何在Android中自动倒计时?

时间:2013-12-14 17:50:01

标签: android timer

我在Android中使用计时器功能,我的代码是1到计时器。请帮我把它作为倒数计时器而不点击按钮?

public class MainActivity extends Activity {

    public int time = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //Declare the timer
        Timer t = new Timer();
        //Set the schedule function and rate
        t.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        TextView tv = (TextView) findViewById(R.id.main_timer_text);
                        tv.setText(String.valueOf(time));
                        time += 1;
                    }

                });
            }

        }, 0, 1000);
    }

1 个答案:

答案 0 :(得分:3)

您可以将CountDownTimer用于此

new CountDownTimer(20000, 1000) {

 public void onTick(long millisUntilEnd) {
     mTextView.setText(String.valueOf(millisUntilEnd / 1000));
 }

 public void onFinish() {
     mTextView.setText("done");
 }
}.start();

这将每秒更新TextView的时间,持续20秒。