您在屏幕截图中显示的弹出效果可以使用Android的内置来实现setError(String)
方法上EditText
小部件。
此外,您还可以使用注释的力量Android 萨里帕尔 https://github.com/ragunathjawahar/android-saripaar我编写的库。
首先添加库:
compile 'com.mobsandgeeks:android-saripaar:2.0.2'
该库使用起来非常简单。在您的活动中注释View
您想要验证的引用,如下例所示。
@Order(1)
private EditText fieldEditText;
@Order(2)
@Checked(message = "You must agree to the terms.")
private CheckBox iAgreeCheckBox;
@Order(3)
@Length(min = 3, message = "Enter atleast 3 characters.")
@Pattern(regex = "[A-Za-z]+", message = "Should contain only alphabets")
private TextView regexTextView;
@Order(4)
@Password(min = 6, scheme = Password.Scheme.ALPHA_NUMERIC_MIXED_CASE_SYMBOLS)
private EditText passwordEditText;
@Order(5)
@ConfirmPassword
private EditText confirmPasswordEditText;
The order
属性指定必须验证字段的顺序。
In your onCreate()
方法实例化一个新的Validator
目的。并打电话validator.validate()
在任何事件侦听器内。
您将收到回调onSuccess
and onFailure
的方法ValidationListener
.
如果您想显示如上图所示的弹出窗口,请执行以下操作,
public void onValidationFailed(View failedView, Rule<?> failedRule) {
if (failedView instanceof Checkable) {
Toast.makeText(this, failedRule.getFailureMessage(), Toast.LENGTH_SHORT).show();
} else if (failedView instanceof TextView) {
TextView view = (TextView) failedView;
view.requestFocus();
view.setError(failedRule.getFailureMessage());
}
}