Android 我的倒计时计时器的毫秒不会根据用户输入而改变
我的问题是: 我从两个NumberPicker获取用户输入。然后,我使用收集到的数字设置我的倒计时计时器的Android 我的倒计时计时器的毫秒不会根据用户输入而改变,android,countdowntimer,Android,Countdowntimer,我的问题是: 我从两个NumberPicker获取用户输入。然后,我使用收集到的数字设置我的倒计时计时器的millisInFuture。但问题是:无论我选择什么数字,我的倒计时计时器的millisuntiltfinished都不会根据用户输入而改变。 我的代码简化如下: int firstMin = 1; int firstSec = 30;//initial value in the field int i = 1; //to determine whether the remained ti
millisInFuture
。但问题是:无论我选择什么数字,我的倒计时计时器的millisuntiltfinished
都不会根据用户输入而改变。
我的代码简化如下:
int firstMin = 1;
int firstSec = 30;//initial value in the field
int i = 1; //to determine whether the remained time should be shown
private void initFirstMinPicker() {
minPicker.setMaxValue(60);
minPicker.setValue(firstMin);//set the current value of number picker
minPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
firstMin = newVal;//pass the selected int to firstMin
}
});
//My countdown timer is supposed to start on clicking a button
firstTimer = new CountDownTimer(firstMin * 60000, 500) {//use 500 to
avoid skipping the last onTick()
@Override
public void onTick(long millisUntilFinished) {
Log.d("TAG", "onTick:firstMin " + firstMin);
if (i % 2 == 0) {
workLeft.setText(String.valueOf(millisUntilFinished / 1000));
}
i++;
}
@Override
public void onFinish() {
}
};
我的标签:
D/TAG: onTick:firstMin 6
D/TAG: onTick:firstMin 6
D/TAG: onTick:firstMin 6
很明显,
firstMin
已经更改,但是当我使用firstMin*60000
作为参数时,millisuntiltfinished
将始终从60000开始,无论firstMin*60000
的计算结果是多少。也就是说,当我的倒计时计时器开始倒计时时,它总是从60开始向下计数(初始值为firstMin*60)。我不知道为什么会这样。你们有没有遇到过这样的问题?非常感谢任何帮助。您只声明了一次firstTimer
,这意味着只有当firstmin=1
时才会创建它。每当调用onValueChanged
时,您需要创建一个新的firstTimer
实例,例如:
minPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
firstMin = newVal;//pass the selected int to firstMin
firstTimer = new CountDownTimer(firstMin * 60000, 500) { ... }
}
});
还值得创建一个函数,返回一个新的
CountDownTimer
,只取firstMin
的值,并自动填充其余的默认值,以避免不必要的代码重复 您只声明了firstTimer
一次,这意味着只有当firstmin=1
时才会创建它。每当调用onValueChanged
时,您需要创建一个新的firstTimer
实例,例如:
minPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
firstMin = newVal;//pass the selected int to firstMin
firstTimer = new CountDownTimer(firstMin * 60000, 500) { ... }
}
});
还值得创建一个函数,返回一个新的
CountDownTimer
,只取firstMin
的值,并自动填充其余的默认值,以避免不必要的代码重复 是的,它起作用了。非常感谢你。我也会尝试一下你的建议:)是的,它有效。非常感谢你。我也会试试你的建议:)