2011-08-12 47 views
53

我想在我的ProgressDialog中設置取消按鈕。下面是我的代碼:如何在進度對話框中設置取消按鈕?

myDialog = new ProgressDialog(BaseScreen.this); 
myDialog.setMessage("Loading..."); 
myDialog.setCancelable(false); 
myDialog.show(); 

我想對這款ProgressDialogonClickListener設置按鈕。 我用這段代碼試過了:

myDialog.setButton("Cancel", new OnClickListener() {   
    @Override 
    public void onClick(DialogInterface dialog, int which) { 
     // TODO Auto-generated method stub   
     myDialog.dismiss(); 
    } 
}); 

但它不工作。我也嘗試了其他類似的聽衆,但仍然沒有成功。 我該如何解決這個問題?

回答

126

您正在使用的setButton方法已過時(儘管它應該仍然有效)。另外,您可能需要在顯示對話框之前添加按鈕。嘗試:

myDialog = new ProgressDialog(BaseScreen.this); 
myDialog.setMessage("Loading..."); 
myDialog.setCancelable(false); 
myDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { 
    @Override 
    public void onClick(DialogInterface dialog, int which) { 
     dialog.dismiss(); 
    } 
}); 
myDialog.show(); 
+6

僅供參考,'dialog.dismiss()'是不是必要的'onClick'監聽器,因爲它會自動關閉對話框。事實上,這種方法不允許你阻止對話被解僱。 –

17

調用myDialog.show();
你也可以使用myDialog.setButton("Cancel", (DialogInterface.OnClickListener) null);如果你只需要關閉按鈕單擊該對話框之前,請務必讓myDialog.setButton

2

檢查這個

private void createCancelProgressDialog(String title, String message, String buttonText) 
{ 
    cancelDialog = new ProgressDialog(this); 
    cancelDialog.setTitle(title); 
    cancelDialog.setMessage(message); 
    cancelDialog.setButton(buttonText, new DialogInterface.OnClickListener() 
    { 
     public void onClick(DialogInterface dialog, int which) 
     { 
      // Use either finish() or return() to either close the activity or just the dialog 
      return; 
     } 
    }); 
    cancelDialog.show(); 
} 

那麼就使用從其他地方簡單的調用方法,在您的活動

createCancelProgressDialog("Loading", "Please wait while activity is loading", "Cancel"); 
+0

4.3或以上取消 –

相關問題