java - How to do I retrieve the current time on a stopwatch? -
in short, how retrieve time , display on textview elsewhere? variant stop watch lapping automatically updates view when timer stops?
if know resources on proper lapping or other examples of android studio time tracking features please include them.
here working. java stop watch code:
package com.example.temp1.stackoverflowquestion; import android.os.handler; import android.os.systemclock; import android.support.v7.app.appcompatactivity; import android.os.bundle; import android.view.view; import android.widget.button; import android.widget.textview; public class mainactivity extends appcompatactivity { //timer text , button textview txttimer; button btn; //stop watch logic handler handler; long starttime,timeinmilliseconds,timebuff,updatetime =0l; int seconds, minutes, milliseconds; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); txttimer = (textview) findviewbyid(r.id.timer_value); btn = (button)findviewbyid(r.id.btnstart_stop); btn.settext("start"); handler = new handler() ; //start/stop timer , change text btn.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { if (btn.gettext().tostring() == "start") { btn.settext("stop"); starttime = systemclock.uptimemillis(); handler.postdelayed(runnable, 0); } else { btn.settext("start"); timebuff += timeinmilliseconds; handler.removecallbacks(runnable); } } }); } //stop watch logic public runnable runnable = new runnable() { @override public void run() { timeinmilliseconds = systemclock.uptimemillis()-starttime; updatetime = timebuff+timeinmilliseconds; seconds=(int)(updatetime/1000); minutes=seconds/60; seconds%=60; milliseconds=(int)(updatetime%1000); txttimer.settext(""+minutes+":" +string.format("%02d",seconds)+":" +string.format("%03d",milliseconds)); handler.postdelayed(this,0); } }; }
here's .xml layout code:
<textview android:id="@+id/timer_value" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:textcolor="#000" android:layout_margin="20dp" android:text="00:00:00" android:textsize="50sp"/> <button android:id="@+id/btnstart_stop" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="15dp"/>
i figured out. on click have call text view , set text within it.
here example works in code provided in question, add in on click method:
txtview.settext(txttimer.gettext().tostring());
Comments
Post a Comment