The Sudoku game that was written yesterday needs to increase the timer function, using the chronometer implementation as follows, because chronometer itself after the call stop after the background timer will continue to increase, so the pause feature requires additional implementation:
Add the following code to the StartActivity OnCreate method:
TextView =(TextView) Findviewbyid (r.id.time_text); Timer=(chronometer) Findviewbyid (r.id.chronometer); Timer.setbase (Systemclock.elapsedrealtime ()+timewhenstopped); Timer.start ();p Ausebutton=(Button) Findviewbyid (r.id.pause);p Ausebutton.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {Pauseorstart++; if(pauseorstart% 2 = = 1) {Toast.maketext (startactivity. This, "Pause", Toast.length_short). Show (); timewhenstopped= Timer.getbase ()-Systemclock.elapsedrealtime (); Timer.stop (); } Else{toast.maketext (startactivity). This, "Start", Toast.length_short). Show (); Timer.setbase (Systemclock.elapsedrealtime ()+timewhenstopped); Timer.start (); } }});
Add the following in the Activity_start.xml:
<LinearLayoutAndroid:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:paddingtop= "5DP"android:orientation= "Horizontal"> <TextViewAndroid:id= "@+id/time_text"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Time:"android:textsize= "30SP"Android:textcolor= "@color/green"Android:layout_weight= "2"/> <chronometerAndroid:id= "@+id/chronometer"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:format= "%s"android:textsize= "30SP"Android:textcolor= "@color/green"Android:layout_weight= "+"/> <ButtonAndroid:id= "@+id/pause"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Pause"Android:textcolor= "@color/green"Android:background= "@drawable/shape2"Android:layout_weight= "1"/></LinearLayout>
The implementation of the chronometer with the pause function can be consulted here:
Http://stackoverflow.com/questions/5594877/android-chronometer-pause
classPausablechronometerextendschronometer {Private Longtimewhenstopped = 0; PublicPausablechronometer (Context context) {Super(context); } PublicPausablechronometer (Context context, AttributeSet attrs) {Super(context, attrs); } PublicPausablechronometer (context context, AttributeSet attrs,intDefstyle) { Super(context, attrs, Defstyle); } @Override Public voidstart () {SetBase (Systemclock.elapsedrealtime ()+timewhenstopped); Super. Start (); } @Override Public voidStop () {Super. Stop (); timewhenstopped= GetBase ()-Systemclock.elapsedrealtime (); } Public voidReset () {stop (); SetBase (Systemclock.elapsedrealtime ()); timewhenstopped= 0; } Public LongGetCurrentTime () {returntimewhenstopped; } Public voidSetcurrenttime (LongTime ) {timewhenstopped=Time ; SetBase (Systemclock.elapsedrealtime ()+timewhenstopped); }}
Android app adds timers