2012-04-25 29 views
4

有沒有一種方法可以在運行時禁用AlertDialog的肯定按鈕,比如說在TextWatcher中?如何在運行時禁用AlertDialog的正向按鈕?

AlertDialog.Builder(this) 
        .setTitle(getString(R.string.createvfs)) 
        .setView(newVSView_v11) 
        .setPositiveButton(getString(R.string.okay), 
          new DialogInterface.OnClickListener() { 

           @Override 
           public void onClick(DialogInterface dialog, 
             int whichButton) { 
           } 
          }) 
        .setNegativeButton(getString(R.string.cancel), 
          new DialogInterface.OnClickListener() { 
           @Override 
           public void onClick(DialogInterface dialog, 
             int whichButton) { 
            // Canceled. 
           } 
          }).show(); 

回答

7

你需要爲了以後修改它,所以你必須改變你的建設者一點,以獲得到對話框本身的引用,但你可以調用AlertDialog.getButton()啓用或禁用按鈕任何時候你喜歡。像這樣的東西...

//Use create() so you can get the instance back 
AlertDialog dialog = AlertDialog.Builder(this) 
       .setTitle(getString(R.string.createvfs)) 
       .setView(newVSView_v11) 
       .setPositiveButton(getString(R.string.okay), 
         new DialogInterface.OnClickListener() { 

          @Override 
          public void onClick(DialogInterface dialog, 
            int whichButton) { 
          } 
         }) 
       .setNegativeButton(getString(R.string.cancel), 
         new DialogInterface.OnClickListener() { 
          @Override 
          public void onClick(DialogInterface dialog, 
            int whichButton) { 
           // Canceled. 
          } 
         }).create(); 
//Then show it 
dialog.show(); 

/* ...Sometime in the distance future... */ 
dialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false); 

如果你想實際上使按鈕不可見,那就更難了。我不能在此刻是否在按鈕上調用setVisibility()會產生良好的效果還是不考?

HTH

+4

我HUST要禁用按鈕,我想你的代碼,但它的fs因爲dialog.getButton (DialogInterface.BUTTON_POSITIVE)返回null。 :S – 2012-04-25 23:03:09