0

嗨,我有以下 2 个功能,想知道是否可以根据布尔值是真还是假(如果用户在 EditText 中输入文本)来阻止下面的“Positivebutton”?

    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;
        }
4

2 回答 2

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);
   }
}

您现在还可以尝试其他阻止按钮的方法,因为您可以访问它。

于 2012-11-15T17:53:10.193 回答
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();

像这样的东西。没测试。

于 2012-11-15T18:00:35.057 回答