2012-07-24 184 views
6

我有6個EditText字段在一個xml ..按鈕單擊我需要驗證是否所有的EditText都有值或它是空的。 目前我正在逐一檢查每個EditText ..我怎樣才能一次檢查所有。檢查是否所有EditText都爲空

代碼

private Button BtnSave; 
EditText ev_last_name,ev_first_name,ev_email,ev_password,ev_confirm_password,ev_phone; 
String last_name,first_name,email,password,confirm_password,phone; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.signup); 
    BtnSave=(Button) findViewById(R.id.BtnSave); 
    ev_last_name=(EditText)findViewById(R.id.edit_lname); 
    ev_first_name=(EditText)findViewById(R.id.edit_fname); 
    ev_email=(EditText)findViewById(R.id.edit_email); 
    ev_password=(EditText)findViewById(R.id.edit_passwd); 
    ev_confirm_password=(EditText)findViewById(R.id.edit_cpasswd); 
    ev_phone=(EditText)findViewById(R.id.edit_phone); 



    BtnSave.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      last_name=ev_last_name.getText().toString(); 
      first_name=ev_first_name.getText().toString(); 
      email=ev_email.getText().toString(); 
      password=ev_password.getText().toString(); 
      confirm_password=ev_confirm_password.getText().toString(); 
      phone=ev_phone.getText().toString(); 

      if ((ev_last_name.getText().toString().length() <= 0)) 
      { 
       System.out.println(" The EditText is empty"); 
       //I will use the toast later 
      } 


     } 
    }); 


} 
+0

檢查逐一總是會更好! – Shobhit 2012-07-24 14:09:33

回答

25

使用 「爲」 循環。

private boolean validate(EditText[] fields){ 
    for(int i = 0; i < fields.length; i++){ 
     EditText currentField = fields[i]; 
     if(currentField.getText().toString().length() <= 0){ 
      return false; 
     } 
    } 
    return true; 
} 

和使用這樣的方法:如果所有的領域都是非空

boolean fieldsOK = validate(new EditText[] { ev_last_name, ev_first_name, ev_email }) 

將返回true。

+0

謝謝你的回覆! – 2012-07-24 14:26:33

1
private boolean isEmptyField (EditText editText){ 
    boolean result = editText.getText().toString().length() <= 0; 
    if (result) 
     Toast.makeText(context, "Fill all fielsd!", Toast.LENGTH_SHORT).show(); 
    return result; 
} 

BtnSave.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      if (isEmptyField(ev_last_name)) return; 
      if (isEmptyField(ev_first_name)) return; 


      // your logic here; 
      ... 

     } 
    }); 
+0

感謝您的回答Georgy :) – 2012-07-24 14:31:58

0
EditText resultInput = (EditText)findViewById(R.id.result); 

if(resultInput.getText().length() > 0) 
// Edit Text is Empty 
else 
// Edit Text is Empty 
+0

請解釋OP的代碼有什麼問題,以及如何通過編輯您的問題解決問題*。* – 2014-09-10 11:37:22