2011-02-15 72 views
2

我想顯示一個進度消息時選擇的偏好:不適用於參數

 Preference prefLocation = (Preference) findPreference("location"); 
    prefLocation.setOnPreferenceClickListener(new OnPreferenceClickListener() { 

     public boolean onPreferenceClick(Preference preference) { 
      ProgressDialog pDialog = ProgressDialog.show(this, "Location" , "Finding location...", true); 
      return true; 
     } 
    }); 

但是我得到在Eclipse中的錯誤:

The method show(Context, CharSequence, CharSequence, boolean) in the type ProgressDialog is not applicable for the arguments (new Preference.OnPreferenceClickListener(){}, String, String, boolean) 

然而,當我在setOnPreferenceClickListener之前執行該行,它編譯得很好!

我可能泄露我在Java中嚴重缺乏經驗,但將appreate線索!

回答

6

這是因爲在這種情況下,您傳遞的是對內聯活動(OnPreferenceClickListener)的引用,而不是上下文(通常必須是您的活動)。改變它並且它將工作:

ProgressDialog pDialog = ProgressDialog.show(NameOfYourActivity.this, "Location" , "Finding location...", true); 
+0

多德感謝.... – 2011-02-15 20:19:52

3

你必須仔細閱讀,仔細閱讀編譯器發出的錯誤信息。

編譯器抱怨這一行:

ProgressDialog pDialog = ProgressDialog.show(this, "Location" , "Finding location...", true); 

ProgressDialog.show()方法需要Context作爲第一個參數。

您通過thisOnPreferenceClickListener類中,所以你傳遞一個OnPreferenceClickListener而不是Context的。

+0

是的,對不起,這讓100%的意義,現在,我知道了「這個」到處是要字節我一些或其他時間! – 2011-02-16 06:02:13

1

this在此上下文中是OnPreferenceClickListener,而不是外部類。

如果你想指的是,你必須做

ProgressDialog pDialog = ProgressDialog.show(YourClassName.this, "Location" , "Finding location...", true); 

YourClassName是班級的偏好活動(或任何你在)的。

+0

非常感謝EboMike。 – 2011-02-16 06:03:33

0

我用這對我的異步Task.this就像魅力的作品。

 @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 

      dialog = new ProgressDialog(ActivityAddTicket.this); 
      dialog.setTitle(R.string.processing); 
      dialog.setMessage(getResources().getString(R.string.loading)); 
      dialog.show(); 
     };