Reputation:
I am implementing a timer in android with one text view and one button for start/stop.
How do I set register different events on clicklistener of the same button, such that when it is clicked the first time it will start a timer and when clicked a second time it will stop the timer and report the time between events? I am implementing a timer in android with one text view and one button for start/stop.
How do I set register different events on clicklistener of the same button, such that when it is clicked the first time it will start a timer and when clicked a second time it will stop the timer and report the time between events?
Edit1
what i did is,
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_depth);
findViewById(R.id.btn).setOnClickListener(this);
}
boolean showingFirst = true;
public void generate(View view){
if(showingFirst){
long startTime = System.currentTimeMillis();
showingFirst = false;
}else{
long difference = System.currentTimeMillis() - startTime;
showingFirst = true;
TextView myText = (TextView)findViewById(R.id.tv);
myText.setText(String.valueOf(difference));
}
}
but since long starttime is started in if when the control enters else loop it shows cannot resolve symbol 'startTime'
please help and special thanks to eliamyro
Upvotes: 0
Views: 102
Reputation: 308
You can do it using a global boolean isStart
and start or stop the timer depending on the value of the isStart
.
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isStart) {
// Stop timer
isStart = false;
} else {
// Start timer
isStart = true;
}
}
});
Upvotes: 1
Reputation: 1642
As you are starting and stopping a Timer
with your button you can just check if the timer is running or not. I would suggest extending a TimerTask
for that use case (I took that code from here):
public class YourTimerTask extends TimerTask {
private boolean isRunning = false;
@Overrides
public void run() {
this.isRunning = true;
//rest of run logic here...
}
public boolean isRunning() {
return this.isRunning;
}
}
Then in your onClickListener
you can just check if your timer is running or not:
startStopBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (yourTimer.isRunning()) {
stopTimer();
} else {
startTimer();
}
}
});
Upvotes: 0
Reputation: 436
on click (start/stop) button start the timer according to your code and return a value to button and when you click again that flag value can be used to create a if condition for stop as well as start
Upvotes: 0
Reputation: 743
try this,
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(btn.getText().toString().equals("Start")){
btn.setText("Stop");
// start timer
}else{
btn.setText("Start");
// stop timer
}
}
});
Upvotes: 0