0

可能重複:
Dismiss a custom dialog?setOnClickListener引發錯誤

我有一個自定義對話框,對話框的佈局文件包含ID按鈕submit_btn」 。

在Java代碼中,我setOnClickListener到對話框的submit_btn按鈕:

View view = layoutInflater.inflate(R.layout.info_dialog, null); 

AlertDialog infoDialog = new AlertDialog.Builder(MyActivity.this) 
              .setView(view)   
              .create(); 
infoDialog.show(); 

Button submitBtn = (Button) view.findViewById(R.id.submit_btn); 

submitBtn.setOnClickListener(new OnClickListener() { 

      public void onClick(View v) { 
     //ERROR: Cannot refer to a non-final variable infoDialog inside an inner class defined in a different method 

        infoDialog.dismiss(); 
     } 
}); 

然後,當我打電話infoDialog.dismiss();,Eclipse的提高其抱怨Cannot refer to a non-final variable infoDialog inside an inner class defined in a different method錯誤。如何根據我的代碼擺脫這個問題?

+0

杜普洛:http://stackoverflow.com/questions/2825272/dismiss-一個自定義對話框 – 2012-02-27 15:55:19

+0

使它最終? – WarrenFaith 2012-02-27 16:04:38

+0

如果您反對將其作爲最終答案,我對該答案進行了編輯。是否有理由不想最終標出它? – bytebender 2012-02-27 16:59:56

回答

0

你可能只是這樣做......

final AlertDialog infoDialog = new AlertDialog.Builder(MyActivity.this) 
              .setView(view)   
              .create(); 

// just add final to that line. 

或者你可以增加infoDialog的範圍。

public class YourActivity { 

    private AlertDialog mInfoDialog; 

    private YourMethod() { 
     View view = layoutInflater.inflate(R.layout.info_dialog, null); 

     mInfoDialog = new AlertDialog.Builder(MyActivity.this) 
              .setView(view)   
              .create(); 
     mInfoDialog.show(); 

     Button submitBtn = (Button) view.findViewById(R.id.submit_btn); 

     submitBtn.setOnClickListener(new OnClickListener() { 

      public void onClick(View v) { 
       mInfoDialog.dismiss(); 
      } 
     }); 
    } 
} 
0

使用

final AlertDialog infoDialog = new AlertDialog.Builder(MyActivity.this) 
             .setView(view)   
             .create(); 
+0

任何其他方式擺脫問題? – 2012-02-27 15:53:53

0
AlertDialog infoDialog = new AlertDialog.Builder(MyActivity.this) 
             .setView(view) 
             .setPositiveButton("ok", /*OnClickListenerGoesHere*/)  
             .create(); 

將解決您的問題,以及關閉該對話框被點擊的按鈕時。

+0

但事情是在我的項目中,我需要避免使用對話框默認按鈕 – 2012-02-27 15:57:40

+0

我不會推薦這麼做,因爲這是'AlertDialog'設計的。但是正如其他人所說的,你可以簡單地在聲明中添加一個「final」。 – keyboardsurfer 2012-02-27 16:02:44

0

使infoDialog作爲類的私有成員或提前在最後加上關鍵字作爲 最終AlertDialog infoDialog =新AlertDialog(...)