我的倒数计时器有些问题。我基本上有一个在其中设置值的微调器。这是微调器的代码:
tSpin1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(i == 0){
timeInms1 = 8400000;
}
if (i == 1){
timeInms1 = 13200000;
}
if (i == 2){
timeInms1 = 18000000;
}
if(i == 3){
timeInms1 = 22800000;
}
if(i == 4){
timeInms1 = 27600000;
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
然后我想将选择传递给倒计时器,以便根据用户之前在微调器中所做的选择,使计时器倒计时给定的时间。下面是倒数计时器的代码:
final CountDownTimer lumbyTree = new CountDownTimer(timeInms1,1000) {
@Override
public void onTick(long lumbyTreeTimeToGo) {
int mins = (int)lumbyTreeTimeToGo/60000;
int seconds = (int)(lumbyTreeTimeToGo-(mins*60000))/1000;
tTimer1.setText(mins +":" +seconds);
}
@Override
public void onFinish() {
tTimer1.setText("00:09");
}
};
tStart1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
lumbyTree.start();
}
});
问题是,我认为&#39; timeInms1&#39;变量由于某种原因永远不会得到值。计时器直接进入onFinish方法。我把一些随机测试语句放入微调器中,如果&#39;括号以确保它正常运行(例如更改textView中的文本)并且它按预期运行,括号中的内容正确执行。我也尝试用随机值(例如30000)初始化timeInms1并运行,但没有改变,它只运行定时器30秒。让我感到困惑的是,当我将诸如setText之类的代码放入&#39; spinner&#39;它会执行的括号,但是当我去改变&#39; TimeInms1&#39;的值时它不起作用。
提前感谢您的帮助!
答案 0 :(得分:0)
你的MainActivity .java看起来应该是这样的
public class MainActivity extends Activity {
CountDownTimer lumbyTree;
Textview tTimer1;
int timeInms1;
private void createCountDownTimer() {
lumbyTree = new CountDownTimer(timeInms1,1000) {
@Override
public void onTick(long lumbyTreeTimeToGo) {
int mins = (int)lumbyTreeTimeToGo/60000;
int seconds = (int)(lumbyTreeTimeToGo-(mins*60000))/1000;
tTimer1.setText(mins +":" +seconds);
}
@Override
public void onFinish() {
tTimer1.setText("00:09");
}
};
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button tStart1=(Button)findViewById(R.id.button1);
tStart1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
createCountDownTimer();
lumbyTree.start();
}
});
Spinner tSpin1 = (Spinner)findViewById(R.id.spinner1);
tSpin1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(i == 0){
timeInms1 = 8400000;
}
if (i == 1){
timeInms1 = 13200000;
}
if (i == 2){
timeInms1 = 18000000;
}
if(i == 3){
timeInms1 = 22800000;
}
if(i == 4){
timeInms1 = 27600000;
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}