[Java] view Plaincopyprint?
<?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" ><chronometerandroid: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= "Start timing"/> <item android:id= "@+id/timer_stop" Andro id:title= "Stop timing"/> <item android:id= "@+id/timer_reset" android:title= "Clear 0"/></menu>
Main activity:
public class mainactivity extends activity {private chronometer timer;@ Overridepublic void oncreate (bundle savedinstancestate) {super.oncreate (savedInstanceState); Setcontentview (R.layout.main);// Gets the Timer object timer = (chronometer) This.findviewbyid (R.id.chronometer )///long press the timer, the context menu This.registerforcontextmenu (timer) appears;} Create context menu @overridepublic void oncreatecontextmenu (Contextmenu menu, view v, Contextmenuinfo menuinfo) {super.oncreatecontextmenu (menu, v, menuinfo);// ContextMenu item does not support icon, so it is not necessary to set icons for them in the resource file if (V.getid () == r.id.chronometer) {// Load the XML menu layout file This.getmenuinflater (). Inflate (R.menu.context_menu, menu);// set the head icon Menu.setheadericon ( R.drawable.icon); // Set Header header Menu.setheadertitle (" Timer control options ");}} After you select the menu item, the response @overridepublic boolean oncontextitemselected (Menuitem item) {switch ( Item.getitemid ()) {case r.id.timer_start:// Clear the Timer 0 timer.setbase (Systemclock.elapsedrealtime ()); //start timing timer.start (); break;case r.id.timer_ stop://Stop Chronograph timer.stop () break;case r.id.timer_reset://the timer 0 timer.setbase (Systemclock.elapsedrealtime ()); break;} return super.oncontextitemselected (item);}}
Operation Result:
Long press the Timer popup context menu to select Start timing:
Android Simple Timer