How to set error on EditText using DataBinding Framework MVVM

前端 未结 4 1832
旧巷少年郎
旧巷少年郎 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:01

    You can also add validation on edit text like this.

    Layout file

    
    
    
        
    
            
    
            
    
            
    
            
    
        
    
        
    
            
    
                
    
                    
                
    
    
                
    
                    
                
    
                
            
        
    
    

    BindingUtils

    object BindingUtils {
            @BindingAdapter(value = ["error", "rule", "android:watcher"], requireAll = true)
            @JvmStatic
            fun watcher(textInputLayout: com.google.android.material.textfield.TextInputLayout, errorMsg: String, rule: ValidationRule, watcher: TextWatcher) {
                textInputLayout.editText?.addTextChangedListener(object : TextWatcher {
                    override fun afterTextChanged(p0: Editable?) {
                    }
    
                    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                    }
    
                    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                        textInputLayout.error = null
                        if (rule == ValidationRule.EMPTY && !ValidationUtils.isValidEmail(p0.toString())) textInputLayout.error = errorMsg
                        if (rule == ValidationRule.PASSWORD && !ValidationUtils.isValidPassword(p0.toString())) textInputLayout.error = errorMsg
                    }
                })
            }
        }
    

    ValidationRule

    enum class ValidationRule{
        EMPTY, EMAIL, PASSWORD
    }
    

    Don't forget to set the watcher in fragment or activity like this

    binding.watcher = object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
            }
    
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
    
            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
        }
    

提交回复
热议问题