本文實例為大家分享了Android實現定時器和倒計時的具體代碼,供大家參考,具體內容如下

創新互聯公司專注于薩嘎企業網站建設,成都響應式網站建設公司,商城網站制作。薩嘎網站建設公司,為薩嘎等地區提供建站服務。全流程定制網站,專業設計,全程項目跟蹤,創新互聯公司專業和態度為您提供的服務
直接上代碼,相信都看得懂。
Android已經幫封裝好了一個類,只不過很多人不知道而已。
代碼:
public class SplashActivity extends BaseAppCompatActivity {
@InjectView(R.id.ivBg)
ImageView ivBg;
@InjectView(R.id.tvSkip)
TextView tvSkip;
int[] imgs = new int[]{
R.mipmap.irving,
R.mipmap.bryant,
R.mipmap.james,
R.mipmap.harden,
R.mipmap.curry};
private CountDownTimer timer;
@Override
protected int getContentViewLayoutID() {
return R.layout.activity_splash;
}
@Override
protected void initViewsAndEvents() {
int index = (int) (Math.random() * imgs.length);
ivBg.setImageResource(imgs[index]);
timer = new CountDownTimer(3500, 1000) {
@Override
public void onTick(long millisUntilFinished) {
tvSkip.setText(String.format(getResources().getString(R.string.skip), (int) (millisUntilFinished / 1000 + 0.1)));
}
@Override
public void onFinish() {
tvSkip.setText(String.format(getResources().getString(R.string.skip), 0));
startActivity(new Intent(mContext, HomeActivity.class));
finish();
}
};
timer.start();
}
@OnClick(R.id.tvSkip)
public void skip() {
if (timer != null)
timer.cancel();
startActivity(new Intent(mContext, HomeActivity.class));
finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (timer != null) {
timer.cancel();
}
}
} 調用的時候很簡單:timer.start();
最后說明一下:CountDownTimer timer = new CountDownTimer(3500, 1000)中,第一個參數表示總時間,第二個參數表示間隔時間。意思就是每隔一秒會回調一次方法onTick,然后10秒之后會回調onFinish方法。
布局activity_splash.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/ivBg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY" />
<TextView
android:id="@+id/tvSkip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_margin="10dp"
android:background="@drawable/common_button_selector"
android:padding="5dp"
android:text="@string/skip" />
</RelativeLayout>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持創新互聯。
本文題目:AndroidCountDownTimer實現定時器和倒計時效果
文章起源:http://www.yijiale78.com/article22/pchocc.html
成都網站建設公司_創新互聯,為您提供Google、響應式網站、關鍵詞優化、微信小程序、商城網站、動態網站
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯