0

我有一个计时器,我希望它从用户单击按钮时开始计数,而不是从活动开始时开始计数。目前,当用户单击按钮从 0 开始计时器时,它只显示从 Activity 开始的时间。以下是相关代码:

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.startTimer: {
            Chronometer stopWatch = (Chronometer) findViewById(R.id.chrono);
            startTime = SystemClock.elapsedRealtime();

            timer = (TextView) findViewById(R.id.timerText);
            stopWatch.setOnChronometerTickListener(new OnChronometerTickListener(){
                @Override
                public void onChronometerTick(Chronometer arg0) {
                    countUp = (SystemClock.elapsedRealtime() - arg0.getBase()) / 1000;
                    String asText = (countUp / 60) + ":" + (String.format("%02d", (countUp % 60))); 
                    timer.setText(asText);
                }
            });
            stopWatch.start();
            break;
        }
...

我需要改变什么?

4

2 回答 2

1

不确定 arg0.getBase 是什么,但我认为你想改变——

countUp = (SystemClock.elapsedRealtime() - arg0.getBase()) / 1000;

countUp = (SystemClock.elapsedRealtime() - startTime) / 1000;

因为 startTime 是单击按钮的时间。

于 2012-12-23T05:09:16.510 回答
-1

你可以加

stopWatch.setBase(startTime);

略低于

startTime = SystemClock.elapsedRealtime();

所以,你更新的代码会像,......

@Override
public void onClick(View v) {
switch (v.getId()) {
    case R.id.startTimer: {
        Chronometer stopWatch = (Chronometer) findViewById(R.id.chrono);
        startTime = SystemClock.elapsedRealtime();

        // this line to be added to the code
         stopWatch.setBase(startTime);


        timer = (TextView) findViewById(R.id.timerText);
        stopWatch.setOnChronometerTickListener(new OnChronometerTickListener(){
            @Override
            public void onChronometerTick(Chronometer arg0) {
                countUp = (SystemClock.elapsedRealtime() - arg0.getBase()) / 1000;
                String asText = (countUp / 60) + ":" + (String.format("%02d", (countUp % 60))); 
                timer.setText(asText);
            }
        });
        stopWatch.start();
        break;
    }
...

希望这可以帮助..

于 2017-07-14T18:13:29.043 回答