The example of this article describes the simple timer implementation for Android programming. Share to everyone for your reference, specific as follows:
Here, using ContextMenu (Context menu), Chronometer implements a simple counter.
Main.xml:
<?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
<?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=" starts timing "/> <item
" android:id= Timer_stop "android:title=" termination timer/> <item android:id= "@+id/timer_reset" android:title= "
Qing 0"/>
< /menu>
Main activity:
public class Mainactivity extends activity {private chronometer timer;
@Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Get Timer Object timer = (chronometer) This.findviewbyid (r.id.chronometer);
When the timer is long pressed, the context menu This.registerforcontextmenu (timer) appears;
//Create context menu @Override public void Oncreatecontextmenu (ContextMenu menu, View V, contextmenuinfo menuinfo) {
Super.oncreatecontextmenu (menu, V, menuinfo); ContextMenu item does not support icon, so no more resource files, set icons for them if (v.getid () = = R.id.chronometer) {//Load XML menu layout file this.
Getmenuinflater (). Inflate (R.menu.context_menu, menu);
Set head icon Menu.setheadericon (R.drawable.icon);
Set Header Menu.setheadertitle ("Timer control options");
}///Select Response after menu item @Override public boolean oncontextitemselected (MenuItem item) {switch (Item.getitemid ())
{Case R.id.timer_start://Clear the Timer Timer.setbase (Systemclock.elapsedrealtime ());
Start timing timer.start ();
Break
Case R.ID.TIMER_STOP://Stop timing timer.stop ();
Break
Case R.id.timer_reset://will be timer clear 0 timer.setbase (Systemclock.elapsedrealtime ());
Break
return super.oncontextitemselected (item);
}
}
The results of the run are as shown in the figure:
Long Press Timer pop-up context menu select Start Timer:
I hope this article will help you with the Android program.