0

我正在开发一个 android 应用程序,但我的计时器有问题。当调用 onChronometerTick 方法时,TextView 应该在第 60 秒更新,但第一次在第 58 秒更新。如果您暂停并再次启动计时器,它会在不同的时间更新。我发现 onChronometerTick 方法在我启动计时器时被调用了两次,这就是我的问题所在!有人能帮我吗?谢谢!

这是我的代码:

int br = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    bProg = (Button) findViewById(R.id.bProgram);
    bProg.setOnClickListener(this);

    tv = (TextView) findViewById(R.id.textView1);


    chrono = (Chronometer) findViewById(R.id.chronometer);
    chrono.setBase(SystemClock.elapsedRealtime());
    chrono.setOnChronometerTickListener(this);
    chrono.stop();

}

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.bProgram:
        Log.d(TAG, "bProgram Clicked");
        checkButton();

        // Change the electricity consumption for the given program
        changeConsumption();

        calculateSecondPrice();

        tvCons.setText(String.valueOf(consumption * 1000 + " W"));
        tvPrice.setText(String.valueOf(price + " lv."));

        if (prog > 0) {
            startChronometer();
        }

        if (prog == 0) {
            pauseChronometer();
        }
        break;
    }
}



private void pauseChronometer() {
    timeWhenStopped = chrono.getBase() - SystemClock.elapsedRealtime();

    chrono.stop();
}

private void startChronometer() {
    if (prog == 1) {
        chrono.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
        chrono.start();
    }
}



@Override
public void onChronometerTick(Chronometer chronometer) {
    br++;

    totalPrice += secondPrice;

    if (br == 60) {
        br = 0;
        tv.setText(String.valueOf((double) (totalPrice) / 1000000));
    }
}

}

4

1 回答 1

0

OK I found a way to do it. This helped me: http://iqwen.net/question/53767

于 2013-01-20T15:06:26.007 回答