天文钟节省碎片更换时间

时间:2018-10-08 07:00:33

标签: android android-fragments timer stopwatch chronometer

所以我的应用程序有1个活动和4个片段,其中一个片段带有计时器,以显示经过了多少时间。

它工作正常,但是我有一个问题,就是每次我移到另一个片段并返回时,天文钟都会一直回到00:00。

我知道是因为我的startStopWatch()方法在OnCreateView中,但是有什么方法可以使它从停止的地方继续?

是否可以使用Bundle类解决此问题?如果可以,怎么办?

这是我的Chronometer代码,所有代码都在一个片段中:

public class FirstFragment extends Fragment {
    Chrhonometer chronometer;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_memo, container, false);
        chronometer = view.findViewById(R.id.stop_watch);
        chronometer.setFormat("%s");
        chronometer.setBase(SystemClock.elapsedRealtime());
        startStopWatch();
    }
}

和方法:

private void startStopWatch() {

    if (chronometer.getBase() != 0) {

        chronometer.setBase(SystemClock.elapsedRealtime());

    } else {

        chronometer.setBase(chronometer.getBase() + SystemClock.elapsedRealtime());

    }

    chronometer.start();

}

private void stopStopWatch() {

    chronometer.setBase(SystemClock.elapsedRealtime());
    chronometer.stop();

}

谢谢。

1 个答案:

答案 0 :(得分:1)

尝试此方法

    public class FirstFragment extends Fragment {
            Chrhonometer chronometer;
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
                final View view = inflater.inflate(R.layout.fragment_memo, container, false);
                chronometer = view.findViewById(R.id.stop_watch);
        ChronometerHelper chronometerHelper = new ChronometerHelper();
                startStopWatch();
            }

        private void startStopWatch() {
         if (chronometerHelper.getStartTime() == null) {
                    // If the start date is not defined, set it.
                    long startTime = SystemClock.elapsedRealtime();
                    chronometerHelper.setStartTime(startTime);
                    chronometer.setBase(startTime);
                } else {
                    // Otherwise set the chronometer's base to the original
                    // starting time.
                    chronometer.setBase(chronometerHelper.getStartTime());

                }

                chronometer.start();

        }

private void stopStopWatch() {

    long startTime = SystemClock.elapsedRealtime();
    chronometerHelper.setStartTime(startTime);
    chronometer.setBase(startTime);
    chronometer.stop();

}

        }

创建一个ChronometerHelper类,您将在其中节省开始时间。

    public class ChronometerHelper {

    @Nullable
    private static Long mStartTime;

    @Nullable
    public Long getStartTime() {
        return mStartTime;
    }

    public void setStartTime(final long startTime) {
        this.mStartTime = startTime;
    }
}