1 回答

TA貢獻1844條經驗 獲得超8個贊
使用一種方法進行所有電子郵件驗證
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;
}
}
現在您可以checkEmailValidation()對所有電子郵件使用該方法。
// 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
您可以遵循兩種方式
創建一個
BaseActivity
并將其擴展為 allactivity
。創建一個
class
并創建一個static
方法。
基本活動示例
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并在子項中擴展activities如下
public class ChildActivity extends BaseActivity{
// within this class you can use checkEmailValidation`
}
靜態函數示例
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;
}
}
}
現在您可以method使用class name如下方式調用它
public class YourActivity extends AppCompatActivity{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentView());
// you can use checkEmailValidation like
YourClassName.checkEmailValidation(...)
}
}
添加回答
舉報