android - How to connect a countdowntimer to a button -
i'm working android studio. i'm creating app has countdowntimer , button. when run application, timer automatically runs , if want click button there textview counts how many times press button. want timer starts when press button ,the countdown continue running , stops @ time "0:000" stops counting of clicks. can me? (if helps put code)
@override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); txtcount = (textview)findviewbyid(r.id.textview1); txtcount.settext(string.valueof(count)); btncount = (button)findviewbyid(r.id.button1); final textview textviewtimer = (textview)findviewbyid(r.id.textview2); btncount.setonclicklistener(new view.onclicklistener() { public void onclick(view arg0) { count++; txtcount.settext(string.valueof(count)); } }); new countdowntimer(10000, 1) { public void ontick(long millisuntilfinished) { textviewtimer.settext("" + millisuntilfinished / 1000 + ":" + millisuntilfinished % 1000); } public void onfinish() { textviewtimer.settext("0:000"); } }.start(); }
i don't write rest of code of other things privacy, interested part ;)
edited
you can save link countdowntimer , use anywhere want. , issue can have 2 boolean variables : timerstarts
- responsible start timer once, timerprocessing
- responsible check if timer still processing.
like this:
@override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); txtcount = (textview)findviewbyid(r.id.textview1); txtcount.settext(string.valueof(count)); btncount = (button)findviewbyid(r.id.button1); boolean timerprocessing = false; boolean timerstarts = false; final textview textviewtimer = (textview)findviewbyid(r.id.textview2); //saving link timer object final countdowntimer timer = new countdowntimer(10000, 1) { public void ontick(long millisuntilfinished) { textviewtimer.settext("" + millisuntilfinished / 1000 + ":" + millisuntilfinished % 1000); } public void onfinish() { textviewtimer.settext("0:000"); timerprocessing = false; } }); btncount.setonclicklistener(new view.onclicklistener() { public void onclick(view arg0) { //start timer once when button first click if (!timerstarts){ timer.start(); timerstarts = true; timerprocessing = true; } if (timerprocessing){ count++; txtcount.settext(string.valueof(count)); } } }); }
or can have 1 variable (e.g. timerstarts), check in button listener , set false when timer stops, when click button after timer stopped start again. hope helps.
Comments
Post a Comment