无法解决符号错误

时间:2014-09-03 05:06:16

标签: java android variables listener numberpicker

我一直在尝试并尝试解决这个问题,但随着我所做的每一次改变,都会出现新的错误。我想要做的是存储numberpickers中的值(我可能会看到其中的两个),然后可以在以后使用这些值。一旦我解决了这个问题,我想在下面的Toast消息和一个名为countdown的新活动中使用它们。我收到错误消息,指出mainTime和snoozeTime在MyListener和MyListener2类下是多余的,当我尝试在我的字符串中使用它时“无法解析符号”。

public void openCD(View v) {

    class MyListener implements NumberPicker.OnValueChangeListener {

        @Override
        public void onValueChange(NumberPicker numberPickerMain, int oldVal, int newVal) {
            int mainTime = newVal;
        }
    }

    class MyListener2 implements NumberPicker.OnValueChangeListener {

        @Override
        public void onValueChange(NumberPicker numberPickerSnooze, int oldVal, int newVal) {
            int snoozeTime = newVal;
        }
    }

    String confirmation = "Your shower is set for " + MyListener.mainTime + " minutes with a " 
            + MyListener2.snoozeTime + " minute snooze. Enjoy your shower!";
    Toast.makeText(this.getApplicationContext(), confirmation, Toast.LENGTH_LONG).show();
    Intent countdown=new Intent(this, CountDown.class);
    startActivity(countdown);
}

2 个答案:

答案 0 :(得分:0)

在行中:

int mainTime = newVal;

你在本地声明变量,这意味着它不会在方法之外被识别。

同样适用于:

int snoozeTime = newVal;

为了解决这个问题,请将这些变量声明为实例变量(在类级别),并在分配它们时,只需执行赋值,而不进行声明(声明类型):

mainTime = newVal;

答案 1 :(得分:0)

试试如下:

int mainTime=0,snoozeTime=0; 

public void openCD(View v) {

    class MyListener implements NumberPicker.OnValueChangeListener {

        @Override
        public void onValueChange(NumberPicker numberPickerMain, int oldVal, int newVal) {
            mainTime = newVal;
        }
    }

    class MyListener2 implements NumberPicker.OnValueChangeListener {

        @Override
        public void onValueChange(NumberPicker numberPickerSnooze, int oldVal, int newVal) {
            snoozeTime = newVal;
        }
    }

    String confirmation = "Your shower is set for " + mainTime + " minutes with a " 
            + snoozeTime + " minute snooze. Enjoy your shower!";
    Toast.makeText(this.getApplicationContext(), confirmation, Toast.LENGTH_LONG).show();
    Intent countdown=new Intent(this, CountDown.class);
    startActivity(countdown);
}
相关问题