本文实例为大家分享了Android实现倒计时功能的具体代码,供大家参考,具体内容如下
1、实现效果
如下图所示:
2、代码实现
新建一个名为CountdownTime的项目,activity_main.xml代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<? xml version = "1.0" encoding = "utf-8" ?> < RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" > < TextView android:id = "@+id/countdownTimeTextView" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_centerInParent = "true" android:text = "@string/maxTime" android:textSize = "60sp" /> </ RelativeLayout > |
MainActivity.class代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
public class MainActivity extends AppCompatActivity { /** * 倒计时标记 */ public static final int COUNTDOWN_TIME_CODE = 99999 ; /** * 倒计时间隔 */ public static final int DELAY_MILLIS = 1000 ; /** * 倒计时最大值 */ public static final int MAX_COUNT = 10 ; /** * 文本控件 */ private TextView countdownTimeTextView; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); //初始化文本控件 countdownTimeTextView = findViewById(R.id.countdownTimeTextView); //创建一个handler CountdownTimeHandler handler = new CountdownTimeHandler( this ); //新建一个message Message message = Message.obtain(); message.what = COUNTDOWN_TIME_CODE; message.arg1 = MAX_COUNT; //第一次发送message handler.sendMessageDelayed(message, DELAY_MILLIS); } public static class CountdownTimeHandler extends Handler { /** * 倒计时最小值 */ public static final int MIN_COUNT = 0 ; //创建MainActivity弱引用 final WeakReference<MainActivity> mWeakReference; public CountdownTimeHandler(MainActivity activity) { this .mWeakReference = new WeakReference<>(activity); } @Override public void handleMessage(Message msg) { super .handleMessage(msg); //获取对MainActivity的弱引用 MainActivity activity = mWeakReference.get(); switch (msg.what) { case COUNTDOWN_TIME_CODE: int value = msg.arg1; activity.countdownTimeTextView.setText(String.valueOf(value--)); //循环发送消息的控制 if (value >= MIN_COUNT) { Message message = Message.obtain(); message.what = COUNTDOWN_TIME_CODE; message.arg1 = value; sendMessageDelayed(message, DELAY_MILLIS); } break ; } } } } |
3、快捷键总结
Ctrl+Alt+F:改变变量的域
Ctrl+Alt+T:surrounded with快捷键
Ctrl+P:查看方法的参数
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qingjianduoyun/article/details/80630940