非空格式驗證框架--Validation的使用
android中判斷控制元件是否為空的地方非常之多,比如登入註冊,只要是需要填寫東西的地方基本上都需要判空。
難度不大,但是程式碼相對冗雜,如果整合框架的話就相對簡單多了。
1.新增依賴
- compile 'com.mobsandgeeks:android-saripaar:2.0.3'
2.佈局
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-
android:id="@+id/activity_main"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- android:padding="10dp">
- <EditText
- android:id="@+id/et1"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
-
android:hint="請輸入姓名"
- ......
- <EditText
- android:id="@+id/et6"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:hint="請輸入姓名" />
- <Button
- android:text="Button"
- android:layout_width="match_parent"
-
android:layout_height="wrap_content"
- android:id="@+id/button" />
- </LinearLayout>
3.獲取物件並設定相應判斷型別
- @BindView(R.id.button)
- Button button;
- @BindView(R.id.et1)
- @NotEmpty(messageResId = R.string.errorMessage)//型別
- @Order(1)//第幾個
- EditText et1;
- @BindView(R.id.et2)
- @NotEmpty(messageResId = R.string.errorMessage)
- @Order(2)
- EditText et2;
strings.xml
- <resources>
- <string name="app_name">ValidationDemo</string>
- <string name="errorMessage">不能為空</string>
- </resources>
4.onCreate中初始化
- validator = new Validator(this);
- validator.setValidationListener(this);
兩個監聽方法
- @Override
- publicvoid onValidationSucceeded() {//不為空的時候執行
- //do somethings
- //sendSubmit();
- }
- @Override
- publicvoid onValidationFailed(List<ValidationError> errors) {//為空的時候執行
- for (ValidationError error : errors) {
- View view = error.getView();
- String message = error.getCollatedErrorMessage(this);
- if (view instanceof EditText) {
- ((EditText) view).setError(message);
- }
- }
- }
- @Override
- publicvoid onClick(View view) {
- switch (view.getId()) {
- case R.id.button:
- validator.validate();
- break;
- }
- }
6.擴充套件(非空、郵箱等)
NotEmpty
@NotEmpty(messageId = R.string.validation_name, order = 1)
private EditText mNameEditText;
MaxLength
MinLength
@MinLength(value = 1, messageId = R.string.validation_participants, order = 2)
private EditText mNameEditText;
MaxValue
MinValue
@MinValue(value = 2L, messageId = R.string.validation_name_length)
private EditText mEditNumberOfParticipants;
MaxNumberValue
MinNumberValue
@MinNumberValue(value = "5.5", messageId = R.string.validation_name_length)
private EditText mEditPotentialOfHydrogen;
RegExp
@RegExp(value = EMAIL, messageId = R.string.validation_valid_email)
private EditText mEditEmail;
@RegExp(value = "^[0-9]+$", messageId = R.string.validation_valid_count)
private EditText mEditCount;
DateInFuture
@DateInFuture(messageId = R.string.validation_date)
private TextView mTxtDate;
DateNoWeekend
@DateNoWeekend(messageId = R.string.validation_date_weekend)
private TextView mTxtDate;
Custom
@Custom(value = MyVeryOwnValidator.class, messageId = R.string.validation_custom)
private EditText mNameEditText;