怎么在Android中使用CountDownTimer实现倒计时

怎么在Android中使用CountDownTimer实现倒计时?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

(1)public abstract void onTick(long millisUntilFinished); 

固定间隔被调用
(2)public abstract void onFinish();
倒计时完成时被调用
(3)public synchronized final void cancel():
取消倒计时,当再次启动会重新开始倒计时
(4)public synchronized final CountDownTimer start():
启动倒计时

在这里可以看到前面两个是抽象方法,需要重写。

简单看一下代码:

package com.per.countdowntimer;

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


public class MainActivity extends Activity {
 private TextView mTvShow;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 mTvShow = (TextView) findViewById(R.id.show);
 }

 /**
 * 取消倒计时
 * @param v
 */
 public void oncancel(View v) {
 timer.cancel();
 }

 /**
 * 开始倒计时
 * @param v
 */
 public void restart(View v) {
 timer.start();
 }

 private CountDownTimer timer = new CountDownTimer(10000, 1000) {

 @Override
 public void onTick(long millisUntilFinished) {
  mTvShow.setText((millisUntilFinished / 1000) + "秒后可重发");
 }

 @Override
 public void onFinish() {
  mTvShow.setEnabled(true);
  mTvShow.setText("获取验证码");
 }
 };
}

顺带附上XML布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@android:color/white"
 android:orientation="vertical"
 android:padding="16dp">

 <TextView
 android:id="@+id/show"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="@string/hello_world" />

 <Button
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginTop="10dp"
 android:onClick="restart"
 android:text="取消" />

 <Button
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginTop="10dp"
 android:onClick="oncancel"
 android:text="结束" />

</LinearLayout>

最后说明一下:

CountDownTimer timer = new CountDownTimer(10000, 1000):以毫秒为单位,第一个参数是指从开始调用start()方法到倒计时完成的时候onFinish()方法被调用这段时间的毫秒数,也就是倒计时总的时间;第二个参数表示间隔多少毫秒调用一次 onTick方法,例如间隔1000毫秒。
在调用的时候直接使用timer.start();

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对亿速云的支持。