如何使用 ViewModel 和 Databinding 实现验证?

How to implement validation using ViewModel and Databinding?

使用 ViewModel 和数据绑定验证表单数据的最佳方法是什么?

我有一个链接绑定布局和 ViewModel 的简单注册 activity

class StartActivity : AppCompatActivity() {

    private lateinit var binding: StartActivityBinding
    private lateinit var viewModel: SignUpViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel = ViewModelProviders.of(this, SignUpViewModelFactory(AuthFirebase()))
                .get(SignUpViewModel::class.java);

        binding = DataBindingUtil.setContentView(this, R.layout.start_activity)
        binding.viewModel = viewModel;

        signUpButton.setOnClickListener {

        }
    }
}

ViewModel 与 4 ObservableFieldssignUp() 方法应该在将数据提交到服务器之前验证数据。

class SignUpViewModel(val auth: Auth) : ViewModel() {
    val name: MutableLiveData<String> = MutableLiveData()
    val email: MutableLiveData<String> = MutableLiveData()
    val password: MutableLiveData<String> = MutableLiveData()
    val passwordConfirm: MutableLiveData<String> = MutableLiveData()

    fun signUp() {

        auth.createUser(email.value!!, password.value!!)
    }
}

我想我们可以为每个输入添加四个布尔 ObservableField,在 signUp() 中我们可以检查输入并更改布尔 ObservableField 的状态,这将在布局上产生一个出现的错误

val isNameError: ObservableField<Boolean> = ObservableField()


fun signUp() {

        if (name.value == null || name.value!!.length < 2 ) {
            isNameError.set(true)
        }

        auth.createUser(email.value!!, password.value!!)
    }

但我不确定 ViewModel 是否应该负责验证并向用户显示错误,我们会有样板代码

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <import type="android.view.View" />

        <variable
            name="viewModel"
            type="com.maximdrobonoh.fitnessx.SignUpViewModel" />
    </data>

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorGreyDark"
        android:orientation="vertical"
        android:padding="24dp">

        <TextView
            android:id="@+id/appTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:text="@string/app_title"
            android:textColor="@color/colorWhite"
            android:textSize="12sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <LinearLayout
            android:id="@+id/screenTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:orientation="horizontal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/appTitle">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="4dp"
                android:text="@string/sign"
                android:textColor="@color/colorWhite"
                android:textSize="26sp"
                android:textStyle="bold" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/up"
                android:textColor="@color/colorWhite"
                android:textSize="26sp" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/form"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="24dp"
            android:orientation="vertical"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/screenTitle">

            <android.support.v7.widget.AppCompatEditText
                style="@style/SignUp.InputBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/sign_up_name"
                android:inputType="textPersonName"
                android:text="@={viewModel.name}" />

            <android.support.v7.widget.AppCompatEditText
                style="@style/SignUp.InputBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/sign_up_email"
                android:inputType="textEmailAddress"
                android:text="@={viewModel.email}"
               />

            <android.support.v7.widget.AppCompatEditText
                style="@style/SignUp.InputBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/sign_up_password"
                android:inputType="textPassword"
                android:text="@={viewModel.password}" />

            <android.support.v7.widget.AppCompatEditText
                style="@style/SignUp.InputBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/sign_up_confirm_password"
                android:inputType="textPassword"
                android:text="@={viewModel.passwordConfirm}" />

            <Button
                android:id="@+id/signUpButton"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:background="@drawable/button_gradient"
                android:text="@string/sign_up_next_btn"
                android:textAllCaps="true"
                android:textColor="@color/colorBlack" />

        </LinearLayout>

    </android.support.constraint.ConstraintLayout>
</layout>

其实你的想法是对的。 viewmodel 不应该知道任何关于 android 系统的信息,并且只能在纯 java/kotlin 下工作。因此,做你想做的事是对的。 ViewModel 不应该知道 android 系统,因为所有视图交互都应该在视图上处理。但是,它们的属性可以绑定到视图。

TL;DR

这会起作用

fun signUp() {

    if (name.value == null || name.value!!.length < 2 ) {
        isNameError.set(true)
    }

    auth.createUser(email.value!!, password.value!!)
}


建议

我建议,如果您想深入挖掘,可以使用自定义绑定适配器。这样你:

  • 您的视图模型不需要额外的变量
  • 拥有更清晰的视图模型,因为错误处理是在自定义绑定适配器上进行的
  • 阅读您的 XML 视图会更容易,因为您可以在那里定义您需要的验证

我将让您充分发挥想象力,了解如何使自定义绑定适配器仅具有验证功能。现在,最好了解自定义绑定适配器的基础知识。

干杯

是的,您可以使用来自 ViewModel 的验证逻辑,因为您拥有来自 ViewModel[ 的可观察变量=40=] 并且您的 xml 也从 ViewModel class 中获取数据。

所以,解决方案:

  • 您可以在 ViewModel 中创建 @BindingAdapter 并绑定您的 按钮点击它。在那里检查你的验证并做一些其他的 东西也。

  • 您可以创建Listener,并在ViewModel上实现接收单击按钮并将该侦听器绑定到 xml.

  • 您也可以使用 Two-Way data binding (但要注意无限循环).

    //Let's say it's your binding adapter from ViewModel
    fun signUp() {
       if (check validation logic) {
          // Produce errors
       }
       // Further successful stuffs
    }
    

可以通过多种方式实现这一点。我告诉你两个解决方案,都很好,你可以使用你觉得合适的。

我使用 extends BaseObservable,因为我发现这比将所有字段转换为 Observers 更容易。您也可以使用 ObservableFields

解决方案 1(使用自定义 BindingAdapter

在xml

<variable
    name="model"
    type="sample.data.Model"/>

<EditText
    passwordValidator="@{model.password}"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@={model.password}"/>

Model.java

public class Model extends BaseObservable {
    private String password;

    @Bindable
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
        notifyPropertyChanged(BR.password);
    }
}

DataBindingAdapter.java

public class DataBindingAdapter {
    @BindingAdapter("passwordValidator")
    public static void passwordValidator(EditText editText, String password) {
        // ignore infinite loops
        int minimumLength = 5;
        if (TextUtils.isEmpty(password)) {
            editText.setError(null);
            return;
        }
        if (editText.getText().toString().length() < minimumLength) {
            editText.setError("Password must be minimum " + minimumLength + " length");
        } else editText.setError(null);
    }
}

解决方案 2(使用自定义 afterTextChanged

在xml

<variable
    name="model"
    type="com.innovanathinklabs.sample.data.Model"/>

<variable
    name="handler"
    type="sample.activities.MainActivityHandler"/>

<EditText
    android:id="@+id/etPassword"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:afterTextChanged="@{(edible)->handler.passwordValidator(edible)}"
    android:text="@={model.password}"/>

MainActivityHandler.java

public class MainActivityHandler {
    ActivityMainBinding binding;

    public void setBinding(ActivityMainBinding binding) {
        this.binding = binding;
    }

    public void passwordValidator(Editable editable) {
        if (binding.etPassword == null) return;
        int minimumLength = 5;
        if (!TextUtils.isEmpty(editable.toString()) && editable.length() < minimumLength) {
            binding.etPassword.setError("Password must be minimum " + minimumLength + " length");
        } else {
            binding.etPassword.setError(null);
        }
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    ActivityMainBinding binding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        binding.setModel(new Model());
        MainActivityHandler handler = new MainActivityHandler();
        handler.setBinding(binding);
        binding.setHandler(handler);
    }
}

更新

你也可以替换

android:afterTextChanged="@{(edible)->handler.passwordValidator(edible)}"

android:afterTextChanged="@{handler::passwordValidator}"

因为 android:afterTextChangedpasswordValidator 的参数相同。

此方法使用自定义绑定适配器 TextInputLayouts,并为表单错误创建枚举。我认为结果在 xml 中读起来很好,并将所有验证逻辑保留在 ViewModel 中。

视图模型:

class SignUpViewModel() : ViewModel() {

   val name: MutableLiveData<String> = MutableLiveData()
   // the rest of your fields as normal

   val formErrors = ObservableArrayList<FormErrors>()

   fun isFormValid(): Boolean {
      formErrors.clear()
      if (name.value?.isNullOrEmpty()) {
          formErrors.add(FormErrors.MISSING_NAME)
      }
      // all the other validation you require
      return formErrors.isEmpty()
   }

   fun signUp() {
      auth.createUser(email.value!!, password.value!!)
   }

   enum class FormErrors {
      MISSING_NAME,
      INVALID_EMAIL,
      INVALID_PASSWORD,
      PASSWORDS_NOT_MATCHING,
   }

}

绑定适配器:

@BindingAdapter("app:errorText")
fun setErrorMessage(view: TextInputLayout, errorMessage: String) {
    view.error = errorMessage
}

XML:

<layout>

  <data>

        <import type="com.example.SignUpViewModel.FormErrors" />

        <variable
            name="viewModel"
            type="com.example.SignUpViewModel" />

  </data>

<!-- The rest of your layout file etc. -->

       <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/text_input_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:errorText='@{viewModel.formErrors.contains(FormErrors.MISSING_NAME) ? "Required" : ""}'>

            <com.google.android.material.textfield.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Name"
                android:text="@={viewModel.name}"/>

        </com.google.android.material.textfield.TextInputLayout>

<!-- Any other fields as above format -->

然后,可以从 activity/fragment 调用 ViewModel,如下所示:

class YourActivity: AppCompatActivity() {

   val viewModel: SignUpViewModel
  // rest of class

  fun onFormSubmit() {
     if (viewModel.isFormValid()) {
        viewModel.signUp()
        // the rest of your logic to proceed to next screen etc.
     }
     // no need for else block if form invalid, as ViewModel, Observables
     // and databinding will take care of the UI
  }


}

我写了一个 library 用于验证 Observable 对象的可绑定字段。

设置您的 Observable 模型:

class RegisterUser:BaseObservable(){
@Bindable
var name:String?=""
    set(value) {
        field = value
        notifyPropertyChanged(BR.name)
    }

@Bindable
var email:String?=""
    set(value) {
        field = value
        notifyPropertyChanged(BR.email)
    }

}

实例化并添加规则

class RegisterViewModel : ViewModel() {

var user:LiveData<RegisterUser> = MutableLiveData<RegisterUser>().also {
    it.value = RegisterUser()
}

var validator = ObservableValidator(user.value!!, BR::class.java).apply {
    addRule("name", ValidationFlags.FIELD_REQUIRED, "Enter your name")

    addRule("email", ValidationFlags.FIELD_REQUIRED, "Enter your email")
    addRule("email", ValidationFlags.FIELD_EMAIL, "Enter a valid email")

    addRule("age", ValidationFlags.FIELD_REQUIRED, "Enter your age (Underage or too old?)")
    addRule("age", ValidationFlags.FIELD_MIN, "You can't be underage!", limit = 18)
    addRule("age", ValidationFlags.FIELD_MAX, "You sure you're still alive?", limit = 100)

    addRule("password", ValidationFlags.FIELD_REQUIRED, "Enter your password")

    addRule("passwordConfirmation", ValidationFlags.FIELD_REQUIRED, "Enter password confirmation")
    addRule("passwordConfirmation", ValidationFlags.FIELD_MATCH, "Passwords don't match", "password")
}

}

并设置您的 xml 文件:

<com.google.android.material.textfield.TextInputLayout
style="@style/textFieldOutlined"
error='@{viewModel.validator.getValidation("email")}'
android:layout_width="match_parent"
android:layout_height="wrap_content">

<com.google.android.material.textfield.TextInputEditText
    android:id="@+id/email"
    style="@style/myEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Your email"
    android:imeOptions="actionNext"
    android:inputType="textEmailAddress"
    android:text="@={viewModel.user.email}" />