【问题标题】:Cannot resolve symbol error无法解决符号错误
【发布时间】:2014-09-03 05:06:16
【问题描述】:

我一直在尝试解决这个问题,但是随着我所做的每一次更改,都会出现新的错误。我想做的是存储来自 numberpickers 的值(我有 2 个,你可能会看到),然后以后可以使用这些值。一旦我解决了这个问题,我想在下面的 Toast 消息和一个名为倒计时的新活动中使用它们。我收到错误消息说 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);
}

【问题讨论】:

  • 全局声明您的mainTime, snoozeTime 以在方法外访问其值。

标签: java android variables listener numberpicker


【解决方案1】:

尝试如下:

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);
}

【讨论】:

  • 这与我的回答不同......什么?
  • 不客气,如果有帮助,请将答案标记为正确:) @RebeccaWyler
  • 哎呀,老实说,我什至不知道该怎么做!现在标记为正确。再次感谢您的帮助!
  • @RebeccaWyler 谢谢:)
【解决方案2】:

行内:

int mainTime = newVal;

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

同样适用于:

int snoozeTime = newVal;

为了解决这个问题,将这些变量声明为实例变量(在类级别),当您分配它们时,只需进行分配,无需声明(声明类型):

mainTime = newVal;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-05
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    相关资源
    最近更新 更多