How to set error on EditText using DataBinding Framework MVVM

前端 未结 4 1831
旧巷少年郎
旧巷少年郎 2021-02-19 09:26

I am using Android Data Binding framework I have suppose an EditText for login form with username as below



        
4条回答
  •  无人共我
    2021-02-19 10:05

    I just want to share my modification of the answer of Long Ranger for android arch viewModel:

        public class StringValidationRules {
    
        public static StringRule NOT_EMPTY = new StringRule() {
            @Override
            public boolean validate(Editable s) {
                return TextUtils.isEmpty(s.toString());
            }
        };
    
        public static StringRule EMAIL = new StringRule() {
            @Override
            public boolean validate(Editable s) {
                return !android.util.Patterns.EMAIL_ADDRESS.matcher(s).matches();
    
            }
        };
    
        public static StringRule PASSWORD = new StringRule() {
            @Override
            public boolean validate(Editable s) {
                return s.length() < 8;
            }
        };
    
        public interface StringRule {
            boolean validate(Editable s);
        }
    }
    

    the viewModel...

        public class LoginViewModel extends ViewModel {
    ...
    @BindingAdapter({"app:validation", "app:errorMsg"})
        public static void setErrorEnable(EditText editText, StringValidationRules.StringRule stringRule, final String errorMsg) {
            editText.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    
                }
    
                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    
                }
    
                @Override
                public void afterTextChanged(Editable editable) {
                    if (stringRule.validate(editText.getText())) {
                        editText.setError(errorMsg);
                    } else {
                        editText.setError(null);
                    }
                }
            });
        }
    
    ...
    

    and the XML:

    
    
        
            
            
        
    
    ...
    
    
    
    
    

提交回复
热议问题