CountDownTimer实现按钮倒计时

activity_splash.xml中进行布局:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:tools="http://schemas.android.com/tools"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent"
 6     android:background="@drawable/launch_bg"
 7     tools:context=".activity.SplashActivity">
 8 
 9     <Button
10         android:id="@+id/btn_skip"
11         android:layout_width="wrap_content"
12         android:layout_height="wrap_content"
13         android:layout_alignParentBottom="true"
14         android:layout_centerHorizontal="true"
15         android:text="跳过"
16         android:textColor="#FFFFFF"
17         android:textStyle="bold"
18         android:textSize="18sp"
19         android:background="@drawable/btn_skip"
20         android:layout_marginBottom="70dp"/>
21 
22 </RelativeLayout>

CountDownTimer(5*1000,1000) 第一个参数是总时间,第二个参数是时间间隔,单位为毫秒

 1 public class SplashActivity extends AppCompatActivity {
 2 
 3     private Button btn_skip;
 4     CountDownTimer timer;
 5 
 6     @Override
 7     protected void onCreate(Bundle savedInstanceState) {
 8         super.onCreate(savedInstanceState);
 9         setContentView(R.layout.activity_splash);
10         init();
11     }
12 
13     private void init() {
14         //初始化布局
15         btn_skip = (Button)findViewById(R.id.btn_skip);
16 
17        timer = new CountDownTimer(5*1000,1000) {
18            @Override
19            public void onTick(long l) {//计时过程显示
20 //               btn_skip.setText((l/1000+1) + "秒");
21            }
22 
23            @Override
24            public void onFinish() {  //计时完毕时触发
25                //界面跳转
26                 Intent intent = new Intent(SplashActivity.this,MainActivity.class);
27                 startActivity(intent);
28                 //关闭SplashActivity
29                 SplashActivity.this.finish();
30            }
31 
32        }.start();
33 
34         btn_skip.setOnClickListener(new View.OnClickListener() {
35             @Override
36             public void onClick(View view) {
37                 //界面跳转
38                 Intent intent = new Intent(SplashActivity.this,MainActivity.class);
39                 startActivity(intent);
40                 //关闭SplashActivity
41                 SplashActivity.this.finish();
42             }
43         });
44 
45     }
46     //销毁timer
47     @Override
48     protected void onDestroy() {
49         super.onDestroy();
50         if (timer!=null) {
51             timer.cancel();
52         }
53     }
54 
55 }

 

posted @ 2019-05-28 19:38  笺笙  阅读(1759)  评论(0编辑  收藏  举报