2012-04-25 66 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