问题
I have a chronometer timer on a fragment and I want it to reset to 00:00 and stops when I press a button.
Here is the code of the fragment:
public class FirstFragment extends Fragment {
Chronometer chronometer;
@Overried
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_memo, container, false);
Button testButton = view.findViewById(R.id.btn_test);
chronometer = view.findViewById(R.id.stop_watch);
chronometer.setFormat("%s");
testButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopStopWatch();
((BottomNavigationView) getActivity().findViewById(R.id.bottom_navigation))
.setSelectedItemId(R.id.nav_second_fragment);
}
});
}
}
And I made a class called StopWatchHelper (Thanks to @Mushahid)
public class StopWatchHelper {
@Nullable
private static Long startTime;
@Nullable
public Long getStartTime() {
return startTime;
}
public void setStartTime(final long startTime) {
this.startTime = startTime;
}
}
And here are my start and stop methods for the chronometer:
private void startStopWatch() {
StopWatchHelper stopWatchHelper = new StopWatchHelper();
if (stopWatchHelper.getStartTime() == null) {
long startTime = SystemClock.elapsedRealtime();
stopWatchHelper.setStartTime(startTime);
chronometer.setBase(startTime);
} else {
chronometer.setBase(stopWatchHelper.getStartTime());
}
chronometer.start();
}
private void stopStopWatch() {
StopWatchHelper stopWatchHelper = new StopWatchHelper();
long startTime = SystemClock.elapsedRealtime();
stopWatchHelper.setStartTime(startTime);
chronometer.setBase(startTime);
chronometer.stop();
}
So the problem is that the timer never stops even if I call the stopStopWatch() method.
It definitely has chronometer.stop(); inside of it, but why does it happen?
The timer resets to 00:00 properly but it keeps counting after the stop method is called.
Is it because it is inside a fragment?
Can anyone help me with this? Thank you.
来源:https://stackoverflow.com/questions/52699035/chronometer-timer-does-not-stop