我是倒数计时器的新手,所以我对这个问题一无所知。我尝试了很多事情,但没有达到我的期望。这是我的计时器代码。和往常一样,它是一个类中的一个类。
// TIMER
public class Timer extends CountDownTimer {
public Timer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
//getNgo(true, score, tries, secLeft);
}
@Override
public void onTick(long millisUntilFinished) {
//secLeft = millisUntilFinished;
int sec = (int) (millisUntilFinished / 1000);
sec = sec % 60;
int min = sec / 60;
tvTime.setTextColor(Color.WHITE);
if (sec <= 10) {
animScale(tvTime);
tvTime.setTextColor(Color.RED);
tvTime.setText("" + min + ":" + sec);
if (sec < 10) {
tvTime.setTextColor(Color.RED);
tvTime.setText("" + min + ":0" + sec);
}
} else {
tvTime.setText("" + min + ":" + sec);
}
}
}
所以,我只是想知道如何在按下按钮时减去3秒(即3000毫秒),textview显示的计时器将继续滴答作响,但时间已经被扣除。以及我在哪里放置代码。谢谢!
当我不得不按计划在固定时间内执行任务时,我已经:
[我怀疑这是比您使用Timer
更标准的模式。
例如:
private final Runnable task = new Runnable() { @Override public void run() { /* ... */ } };
private final ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor();
private final long initialSeconds = 3;
public void submitTask() {
stpe.schedule(task, initialSeconds, TimeUnit.Seconds());
}
public void subtractSeconds(long sec) {
if(stpe.remove(task)) {
stpe.schedule(task, Math.Max(initialSeconds - sec, 0), TimeUnit.Seconds);
}
}
您将需要弄清楚:
final
任务或要更改的任务我已经使用stackoverflow帖子之一实现了简单的倒计时
// gets current time
long timeNow = System.currentTimeMillis();
/* timer holds the values of the current second the timer should display
* requiredTime is the start value that the countdown should start from
* startTime is the time when the application starts
*/
timer = requiredTime - (timeNow - startTime) / 1000;
if (timer >= 0)
timer.setText(String.valueOf(timer));
要减去计时器,请减去requiredTime,它将起作用。因为您已经更改了参考值。
// Override onClickListener and add the line
// to deduct 3 seconds
requiredTime -= 3;
特别感谢@Hadeel Mustafa的回答,它对我有很大帮助!我无法检查完整的示例代码,但它通常可以工作。我仍然有一个问题,我无法解决。我也是Android Studio的新手^^'因此,我可以启动该应用程序,启动并启动countdownTimer,当我单击刑罚按钮时,它会运行一小段时间,然后倒计时运行而不会受到惩罚。但棘手的部分是当倒计时暂停时,然后我单击惩罚。惩罚有效,我单击开始,countdownTimer随惩罚一起运行。
你不能。您必须编写自己的CountDownTimer
。复制原始代码并添加方法
public synchronized void addTime(long millis) {
mStopTimeInFuture += millis;
}
然后将onClickListener
设置为按钮
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
timer.addTime(-2000);
}
});
Here是完整的示例代码