使用ViewModel和Databinding验证表单数据的最佳方法是什么?
我有一个简单的注册活动,该活动将绑定布局和ViewModel链接起来
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 ObservableFields
和signUp()
方法应先验证数据,然后再将数据提交到服务器。
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!!)
}
}
我猜我们可以为每个输入添加四个boolean ObservableField,在signUp()
中,我们可以检查输入并更改boolean 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>
答案 0 :(得分:3)
可以有很多方法来实现这一目标。我告诉您两个解决方案,两个都很好,您可以使用适合自己的解决方案。
我使用extends BaseObservable
是因为与将所有字段都转换为Observers
相比,这很容易。您也可以使用ObservableFields
。
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);
}
}
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:afterTextChanged
和passwordValidator
相同。
答案 1 :(得分:2)
此方法使用TextInputLayouts(一个自定义绑定适配器),并为表单错误创建一个枚举。我认为结果可以很好地在xml中读取,并将所有验证逻辑保留在ViewModel中。
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:
@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 -->
然后,可以从活动/片段中调用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
}
}
答案 2 :(得分:0)
实际上,您的想法是正确的。 viewmodel应该对Android系统一无所知,并且只能与纯Java / kotlin一起使用。因此,做您想的是正确的。 ViewModel不应了解android系统,因为所有视图交互都应在View上处理。但是,它们的属性可以绑定到视图。
这将起作用
fun signUp() {
if (name.value == null || name.value!!.length < 2 ) {
isNameError.set(true)
}
auth.createUser(email.value!!, password.value!!)
}
我建议,如果您想更深入地研究,可以使用“自定义绑定适配器”。这样您:
我会让您的想象力飞向如何使自定义绑定适配器仅具有验证的地方。现在,最好了解自定义绑定适配器的基础。
干杯
答案 3 :(得分:0)
是的,您可以使用 ViewModel
中的验证逻辑,因为您可以使用 ViewModel
中的可观察变量,并且xml是还可以从 ViewModel
类中导出数据。
所以,解决方案:
您可以在ViewModel中创建 @BindingAdapter
并绑定您的
按钮点击它。在此检查您的验证并执行其他操作
东西。
您可以创建 Listener
,并在 ViewModel
上实施,以接收来自按钮的点击并将该监听器绑定到{{ 1}}。
您还可以使用Two-Way data binding (不过要注意无限循环)。
xml
答案 4 :(得分:0)
我发现了几篇关于用Android体系结构组件实现表单验证的文章,大多数解决方案是:“为要编辑的每个字段的模型添加一个属性,并为每个字段错误添加一个属性”。结果,您将获得漂亮的样板代码,但是为什么呢? ViewModel库旨在使我们的生活更轻松,而不是使其复杂化。
如果验证需要访问视图以显示错误,敬酒等等,为什么不将逻辑保留在视图中? ViewModel
加载数据并将其提供给视图,该视图将验证数据并传递回ViewModel
。 View默认情况下会保存诸如EditText
之类的组件的状态,该组件仅应具有ID。尽管绑定了组件,但您不会丢失“活动/片段”娱乐上的已保存状态,因为已保存状态具有更高的优先级。
data class User(
val id: String,
val firstName: String,
val lastName: String
)
class MainVM : ViewModel() {
val user: LiveData<User> = ...
fun save(firstName: CharSequence, lastName: CharSequence) { ... }
}
...
<EditText android:id="@+id/firstNameInput"
android:text="@{model.user.firstName}"
... />
<EditText android:id="@+id/lastNameInput"
android:text="@{model.user.lastName}"
... />
<Button android:onClick="onSaveButtonClick" ... />
...
class MainActivity : AppCompatActivity() {
private lateinit var model: MainVM
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
model = ViewModelProviders.of(this)[MainVM::class.java]
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.lifecycleOwner = this
binding.model = model
}
fun onSaveButtonClick(button: View) {
val firstName = binding.firstNameInput.text.trim()
if (firstName.isBlank()) {
binding.firstNameInput.error = getString(R.string.first_name_is_blank)
return
}
val lastName = binding.lastNameInput.text.trim()
if (lastName.isBlank()) {
binding.lastNameInput.error = getString(R.string.last_name_is_blank)
return
}
model.saveUser(firstName, lastName)
}
}
您可以找到完整的示例here。
答案 5 :(得分:0)
我写了一个library来验证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}" />