本文实例讲述了android编程之简单计时器实现方法。分享给大家供大家参考,具体如下:
这里利用contextmenu(上下文菜单),chronometer实现简单计数器。
main.xml:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<?xml version= "1.0" encoding= "utf-8" ?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:orientation= "vertical" android:layout_width= "fill_parent" android:layout_height = "fill_parent" android:gravity = "center_horizontal" > <chronometer android:id = "@+id/chronometer" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:format= "%s" android:textsize= "80px" android:textcolor= "#00ff00" /> </linearlayout > |
/layout/menu/context_menu.xml
1
2
3
4
5
6
|
<?xml version= "1.0" encoding= "utf-8" ?> <menu xmlns:android= "http://schemas.android.com/apk/res/android" > <item android:id= "@+id/timer_start" android:title= " 开始计时 " /> <item android:id= "@+id/timer_stop" android:title= " 终止计时 " /> <item android:id= "@+id/timer_reset" android:title= " 清零 " /> </menu> |
主activity:
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
|
public class mainactivity extends activity { private chronometer timer; @override public void oncreate(bundle savedinstancestate) { super .oncreate(savedinstancestate); setcontentview(r.layout.main); // 获得计时器对象 timer = (chronometer) this .findviewbyid(r.id.chronometer); //长按计时器时,出现上下文菜单 this .registerforcontextmenu(timer); } //创建上下文菜单 @override public void oncreatecontextmenu(contextmenu menu, view v, contextmenuinfo menuinfo) { super .oncreatecontextmenu(menu, v, menuinfo); // contextmenu的item不支持icon,所以不用再资源文件中,为它们设定图标 if (v.getid() == r.id.chronometer) { //加载xml菜单布局文件 this .getmenuinflater().inflate(r.menu.context_menu, menu); // 设定头部图标 menu.setheadericon(r.drawable.icon); // 设定头部标题 menu.setheadertitle( " 计时器控制选项 " ); } } //选择菜单项后的响应 @override public boolean oncontextitemselected(menuitem item) { switch (item.getitemid()) { case r.id.timer_start: // 将计时器清零 timer.setbase(systemclock.elapsedrealtime()); //开始计时 timer.start(); break ; case r.id.timer_stop: //停止计时 timer.stop(); break ; case r.id.timer_reset: //将计时器清零 timer.setbase(systemclock.elapsedrealtime()); break ; } return super .oncontextitemselected(item); } } |
运行结果如图所示:
长按计时器弹出上下文菜单选择开始计时:
希望本文所述对大家android程序设计有所帮助。