EditText表單驗證(二)
阿新 • • 發佈:2018-11-10
實現
FormValidation
package data; import android.content.Context; import android.support.annotation.NonNull; import android.view.View; import android.widget.EditText; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.self.zsp.dfs.R; import java.math.BigDecimal; import util.KeyboardUtils; import widget.ZsDialog; /** * Created on 2018/10/10. * * @desc 表單驗證 */ public class FormValidation implements View.OnFocusChangeListener { /** * 上下文 */ private Context context; /** * 最大/小值 */ private BigDecimal bigDecimalMin; private BigDecimal bigDecimalMax; /** * 最大/小提示 */ private String minHint; private String maxHint; /** * 規則 */ private int rule; /** * constructor * * @param context 上下文 * @param bigDecimalMin 最小值 * @param minHint 最小提示 * @param rule 規則 */ public FormValidation(Context context, BigDecimal bigDecimalMin, String minHint, int rule) { this.context = context; this.bigDecimalMin = bigDecimalMin; this.minHint = minHint; this.rule = rule; } /** * constructor * * @param context 上下文 * @param bigDecimalMin 最小值 * @param bigDecimalMax 最大值 * @param minHint 最小提示 * @param maxHint 最大提示 * @param rule 規則 */ public FormValidation(Context context, BigDecimal bigDecimalMin, BigDecimal bigDecimalMax, String minHint, String maxHint, int rule) { this.context = context; this.bigDecimalMin = bigDecimalMin; this.bigDecimalMax = bigDecimalMax; this.minHint = minHint; this.maxHint = maxHint; this.rule = rule; } @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { EditText editText = (EditText) v; String stringResult = editText.getText().toString(); if (!"".equals(stringResult)) { // 輸框值 BigDecimal bigDecimalResult = new BigDecimal(stringResult); switch (rule) { // 不小於 case 1: int minCompareResultNotLess = bigDecimalResult.compareTo(bigDecimalMin); if (minCompareResultNotLess < 0) { rangeShow(editText, minHint); } break; // 中間 case 2: int minCompareResultMiddle = bigDecimalResult.compareTo(bigDecimalMin); int maxCompareResultMiddle = bigDecimalResult.compareTo(bigDecimalMax); if (minCompareResultMiddle < 0) { rangeShow(editText, minHint); } else if (maxCompareResultMiddle > 0) { rangeShow(editText, maxHint); } break; default: break; } } } } /** * 顯範圍 * * @param editText 輸框 * @param hint 提示 */ private void rangeShow(final EditText editText, String hint) { ZsDialog.materialStringContentDialogOneClick(context, hint, R.string.refill) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { dialog.dismiss(); KeyboardUtils.showKeyboardEditText(context, editText); } }).cancelable(false).show(); } }
主程式碼
單提
editText.setOnFocusChangeListener(new FormValidation(getContext(), BigDecimal.valueOf(26), "粘度FV不可小於26", 1));
雙提
editText.setOnFocusChangeListener(new FormValidation(getContext(), BigDecimal.valueOf(0), BigDecimal.valueOf(6000), "扭矩不可小於0", "扭矩不可大於6000", 2));