Reputation: 61
When I press the stop button it stops the time from being viewed but still increments in the background. When I press start it shows the entire time that it was stopped. Does anyone know how to make stop actually stop?
import android.app.Fragment;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Chronometer;
public class StopwatchFragment extends Fragment implements OnClickListener {
public StopwatchFragment() {
// Required empty public constructor
}
Button startChron;
Button stopChron;
Button resetChron;
private Chronometer chron;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_stopwatch_main, container, false);
getActivity().getActionBar()
.setTitle("Stopwatch");
startChron = (Button)v.findViewById(R.id.start);
startChron.setOnClickListener(this);
stopChron = (Button)v.findViewById(R.id.stop);
stopChron.setOnClickListener(this);
resetChron = (Button)v.findViewById(R.id.reset);
resetChron.setOnClickListener(this);
chron = (Chronometer) v.findViewById(R.id.chronometer);
return v;
}
@Override
public void onClick(View v) {
if (v == startChron){
chron.start();
}
else if (v == stopChron){
chron.stop();
}
else if (v == resetChron){
chron.setBase(SystemClock.elapsedRealtime());
}
}
}
Upvotes: 0
Views: 567
Reputation: 1080
You're going to have to save in a variable the time when the chrono is paused. Something like this:
difference = chron.getBase() - SystemClock.elapsedRealtime();
And then to set the time when resume:
time = timeDifference + SystemClock.elapsedRealtime()
Upvotes: 1
Reputation: 7070
It is because calling stop()
doesn't changes your Chronometer
base as set using setBase()
. If you want to make your Chronometer
start afresh, then everytime you call start()
you need to setBase()
before it.
chron.setBase(SystemClock.elapsedRealtime());
Check this.
Upvotes: 0