1 回答

TA貢獻(xiàn)1844條經(jīng)驗(yàn) 獲得超8個(gè)贊
使用一種方法進(jìn)行所有電子郵件驗(yàn)證
private boolean checkEmailValidation(EditText e) {
String mail = e.getText().toString()
if (mail.isEmpty()) {
e.setError("Field cannot be empty");
return false;
} else if (!Patterns.EMAIL_ADDRESS.matcher(mail).matches()){
e.setError("Not a valid email");
return false;
} else if (mail.length()>254) {
e.setError("Email to long");
return false;
}else if (mail.length()<5) {
e.setError("Email too short");
return false;
}else {
e.setError(null);
// e.setErrorEnabled(false);
return true;
}
}
現(xiàn)在您可以checkEmailValidation()對(duì)所有電子郵件使用該方法。
// you can check all email like following
if(checkEmailValidation(e.getEditText()) && checkEmailValidation(e1.getEditText()) && checkEmailValidation(e2.getEditText())) {
// do whatever you want here when all email is ok
}else{
// ...
}
要多次使用,activities
您可以遵循兩種方式
創(chuàng)建一個(gè)
BaseActivity
并將其擴(kuò)展為 allactivity
。創(chuàng)建一個(gè)
class
并創(chuàng)建一個(gè)static
方法。
基本活動(dòng)示例
public abstract class BaseActivity extends AppCompatActivity {
private boolean checkEmailValidation(EditText e) {
String mail = e.getText().toString()
if (mail.isEmpty()) {
e.setError("Field cannot be empty");
return false;
} else if (!Patterns.EMAIL_ADDRESS.matcher(mail).matches()){
e.setError("Not a valid email");
return false;
} else if (mail.length()>254) {
e.setError("Email to long");
return false;
}else if (mail.length()<5) {
e.setError("Email too short");
return false;
}else {
e.setError(null);
// e.setErrorEnabled(false);
return true;
}
}
}
BaseActivity并在子項(xiàng)中擴(kuò)展activities如下
public class ChildActivity extends BaseActivity{
// within this class you can use checkEmailValidation`
}
靜態(tài)函數(shù)示例
public class YourClassName{
private static boolean checkEmailValidation(EditText e) {
String mail = e.getText().toString()
if (mail.isEmpty()) {
e.setError("Field cannot be empty");
return false;
} else if (!Patterns.EMAIL_ADDRESS.matcher(mail).matches()){
e.setError("Not a valid email");
return false;
} else if (mail.length()>254) {
e.setError("Email to long");
return false;
}else if (mail.length()<5) {
e.setError("Email too short");
return false;
}else {
e.setError(null);
// e.setErrorEnabled(false);
return true;
}
}
}
現(xiàn)在您可以method使用class name如下方式調(diào)用它
public class YourActivity extends AppCompatActivity{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentView());
// you can use checkEmailValidation like
YourClassName.checkEmailValidation(...)
}
}
添加回答
舉報(bào)