Java 计算处理程序中的剩余时间
我有一个函数,它等待“syncingIntervalsInt”一段时间,然后执行代码。如何创建倒计时?例如,当syncingIntervalsInt设置为10秒时,我想将一个文本视图设置为10、9、8等 以下是我的功能:Java 计算处理程序中的剩余时间,java,android,timer,handler,Java,Android,Timer,Handler,我有一个函数,它等待“syncingIntervalsInt”一段时间,然后执行代码。如何创建倒计时?例如,当syncingIntervalsInt设置为10秒时,我想将一个文本视图设置为10、9、8等 以下是我的功能: public void refreshRecycler() { countingTillSync = syncingIntervalsInt; timerHandler = new Handler(); timerRunnable = new Run
public void refreshRecycler()
{
countingTillSync = syncingIntervalsInt;
timerHandler = new Handler();
timerRunnable = new Runnable() {
@Override
public void run() {
//some code here
countingTillSync--;
}
timerHandler.postDelayed(this, syncingIntervalsInt*1000); //run every second
}
timerHandler.postDelayed(timerRunnable, syncingIntervalsInt*1000); //Start timer after 1 sec
}
上面的代码仅在同步IntervalsInt*1000时间后递减,这不是我所期望的。您可以尝试此方法
1.添加CountDownTimerUtils
public class CountDownTimerUtils extends CountDownTimer {
private TextView mTextView;
/**
* @param textView The TextView
* @param millisInFuture The number of millis in the future from the call
* to {@link #start()} until the countdown is done and {@link #onFinish()}
* is called.
* @param countDownInterval The interval along the way to receiver
* {@link #onTick(long)} callbacks.
*/
public CountDownTimerUtils(TextView textView, long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
this.mTextView = textView;
}
@Override
public void onTick(long millisUntilFinished) {
mTextView.setText(millisUntilFinished / 1000 + "sec");
mTextView.setClickable(false);
}
@Override
public void onFinish() {
mTextView.setText("retry");
mTextView.setClickable(true);
mTextView.setFocusable(true);
}
}
2.这样设置代码。
// 1 param yourTextView was TextView you want to set
// 2 param 10 * 1000 was the number of millis in the future from the call
// 3 param 1000 was the interval along the way to receiver
CountDownTimerUtils mTimerUtils = new CountDownTimerUtils(yourTextView, 10 * 1000, 1000);
mTimerUtils.start();
你能核对一下我的答案吗?