2014-09-03 138 views
0

我一直在試圖弄清楚這一點,但隨着每次更改,新錯誤都會出現。我想要做的是存儲數字選擇器中的值(我可以看到其中的2個),然後可以稍後使用這些值。我想在下面的Toast消息中使用它們,以及在解決此問題後,在一個名爲倒計時的新活動中使用它們。我收到錯誤消息,指出在MyListener和MyListener2類下mainTime和snoozeTime是多餘的,而當我嘗試在我的字符串中使用它們時,「無法解析符號」。無法解決符號錯誤

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

聲明你的'mainTime,snoozeTime'水珠盟友在方法之外訪問其值。 – GrIsHu 2014-09-03 05:20:12

回答

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

這和我的答案有所不同......什麼? – alfasin 2014-09-03 07:21:37

+0

這工作就像一個魅力!非常感謝!!! – 2014-11-05 05:24:14

+0

歡迎您將標記爲正確的答案,如果有幫助:) @RebeccaWyler – GrIsHu 2014-11-05 05:26:51

0

在行:

int mainTime = newVal; 

你聲明變量局部的,這意味着它不會方法的外部識別。

同樣適用於:

int snoozeTime = newVal; 

爲了解決這個問題,聲明這些變量爲實例變量(在類級別),當你給它們,只是做任務,沒有一個聲明(聲明類型):

mainTime = newVal; 
相關問題