2013-01-19 53 views
6

這裏是我的一個對話框代碼,我想禁用正面按鈕,如果要是在大於5編輯文本文字大小,並使其大小< = 5的Android禁止正按鈕在addTextChangedListener(editext)一些condion

private void myDialog(String title) { 
      AlertDialog.Builder builder = new AlertDialog.Builder(context); 


      // Get the layout inflater 
      LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

      View dialogView = inflater.inflate(R.layout.new_dialog, null); 

      // Inflate and set the layout for the dialog 
      // Pass null as the parent view because its going in the dialog layout 
      builder.setView(dialogView); 

      final EditText dialogEdittext = (EditText) dialogView.findViewById(R.id.dialog_editText); 
      final TextView dialogMessage = (TextView) dialogView.findViewById(R.id.dialog_limit); 

      dialogEdittext.addTextChangedListener(new TextWatcher() { 

       @Override 
       public void onTextChanged(CharSequence s, int start, int before, int count) { 
       } 

       @Override 
       public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
       } 

       @Override 
       public void afterTextChanged(Editable s) { 

        // if text length is greater than 5 disable positive button 
           // else enable 
       } 
      }); 

      builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int id) { 

      }); 

      builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int id) { 
       } 
      }); 

      final Dialog dialog = builder.create(); 
      dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); 
      dialog.show(); 

     } 
+0

參考這個鏈接http://stackoverflow.com/questions/8238952/how-to-disable-enable-dialog-negative-possitive-buttons –

+0

我已經看到這個鏈接,它將禁用/啓用按鈕只有一次時,對話框是創建,但我希望每次用戶在edittext中輸入一個字符 – Androider

+0

我從來不這樣做。我已經做了使用自定義對話框與按鈕,並在那檢查驗證。你可以這樣做。嘗試 –

回答

16

嘗試這樣:

@Override 
public void afterTextChanged(Editable s) { 
    if (s.length() > 5) { 
     dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(false); 
    } else { 
     dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(true); 
    } 
} 

其中dialog是:

final AlertDialog dialog = builder.create(); 
+0

對話框無法解析 – Androider

+4

工作,但我不得不移動dialogEdittext.addTextChangedListener .....下面.... dialog.show(); – Androider

+0

@SyedZahidAli這是必需的,因爲你在'dialog'變量創建之前聲明瞭'TextWatcher',所以它看不到它。 – Luksprog