Android CountDownTimer realizes timer and countdown effect
- 2021-08-17 01:07:45
- OfStack
In this paper, we share the specific code of Android timer and countdown for your reference, the specific contents are as follows
I believe you can understand the code directly.
Android has already wrapped a class, but many people don't know it.
Code:
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();
}
}
}
The call is simple: timer. start ();
Under last illustration 1: In CountDownTimer timer = new CountDownTimer (3500, 1000), the first parameter represents the total time and the second parameter represents the interval time. This means that the method onTick will be called back every 1 second, and then the onFinish method will be called back after 10 seconds.
Layout 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>