2012-11-15 149 views
0

嗨我有以下2个函数,并想知道是否有可能阻止下面的“正面按钮”取决于布尔值是true或false(如果用户输入文本或不在EditText中)?禁用AlertDialog按钮?

private void add() { 
      final View addView = getLayoutInflater().inflate(R.layout.add, null); 
      new AlertDialog.Builder(this).setTitle("Add a Book").setView(addView) 
        .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int whichButton) { 
          if(addWord((EditText) addView.findViewById(R.id.titleEdit))){ 
    //Do something, Enable the OK (Positive) button 
} 
else{ 
    Toast.makeText(ActionBarMain.this,"Nothing entered", Toast.LENGTH_LONG).show(); 
//Prevent the user to be able to push the "PositiveButton" (Block it) 
} 


         } 
        }).setNegativeButton("Cancel", null).show(); 
     } 

     private boolean addWord(EditText title){ 
      String mDisplaySting = title.getText().toString(); 
      if(mDisplaySting.matches("")){ 
       Log.i(TAG,"null"); 
       return false;  
      } 
      return true; 
     } 
+0

如何创建一个DialogBu​​ilder对象(“AlertDialog.Builder b = new ...”而不是“新AlertDialog.Builder ...”),然后在if条件中添加positivebutton? – Prexx

回答

0
AlertDialog mAlertDialog = new AlertDialog.Builder(this) 
           .setTitle("Add a Book").setView(addView) 
           .setNegativeButton("Cancel", null); 

if(!edittext.getText().toString().equals("")){ 
    mAlertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int whichButton) { 
         [...] 
        } 
       }); 
} 

mAlertDialog.show(); 

就像这样。没有测试它。

0

你可以禁用如下:

public void onClick(DialogInterface dialog, int whichButton) { 
    if(addWord((EditText) addView.findViewById(R.id.titleEdit))){ 
     // Do something, Enable the OK (Positive) button 
    } else { 
     Toast.makeText(ActionBarMain.this, "Nothing entered", 
      Toast.LENGTH_LONG).show(); 
     //Prevent the user to be able to push the "PositiveButton" (Block it) 
     AlertDialog myDialog = (AlertDialog)dialog; 
     Button button = myDialog.getButton(whichButton); 
     button.setOnClickListener(null); 
    } 
} 

您也可以尝试用阻断按钮,现在你可以访问它的其他方式。