我想用MVVM和数据绑定验证注册用户数据。这是我的代码,请指导我。
活动:
registerViewModel = new ViewModelProvider(this).get(RegisterViewModel.class);
binding.setSignUpObject(new RegisterRequest());
binding.setSignUpClickListener(registerViewModel);
型号:
public class RegisterRequest extends BaseObservable {
@SerializedName("Email")
private String userEmail;
@SerializedName("Password")
private String userPassword;
@Expose
private String userConfirmPassword;
@SerializedName("Phone")
private String userPhone;
@SerializedName("ImagePath")
private String imagePath;
@SerializedName("Name")
private String userName;
@Expose
private RegisterErrors registerErrors;
}
/ 当然是用nonotifyPropertyChanged的setter和用@Bindable注解的getter,我还创建了一个RegisterErrors类,以便在app:error xml上用它来处理错误。
注册错误 :
public class RegisterErrors {
private String userEmailError;
private String userPasswordError;
private String userConfirmPasswordError;
private String userPhoneError;
private String imagePathError;
private String userNameError;
}
XML:
<variable
name="signUpObject"
type="com.rabe7.community.model.request.register.RegisterRequest" />
<variable
name="signUpClickListener"
type="com.rabe7.community.view_model.user_management.RegisterViewModel" />
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="@color/colorBlackTransparent">
<EditText
android:id="@+id/et_sign_up_user_name"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginEnd="@dimen/dp16w"
android:hint="@string/label_sign_up_user_name"
app:error="@{signUpObject.registerErrors.userNameError}"
android:inputType="text"
android:maxLines="1"
android:text="@={signUpObject.userName}"
android:textColor="@color/colorBlack" />
</com.google.android.material.textfield.TextInputLayout>
问题是......我想在点击提交按钮后验证用户的输入......我怎么能在视图模型上用绑定验证呢?
我试试这个。
viewModel:
public void onRegisterSubmitClicked(RegisterRequest registerRequest){
this.registerRequest = registerRequest;
if(registerRequest.getUserName().length()<6){
registerRequest.getRegisterErrors().setUserNameError("error");
}
}
但是 app:error
不工作,我不知道该怎么做......所以帮助我,请:)
你可以在你的ViewModel中这样做。
/**
* Two way bind-able fields
*/
var userName: String = ""
另外,在ViewModel中写一个方法来验证你的屏幕。
fun validateSignupScreen() {
if (userName.isEmpty()) {
return
} else if (userPassword.isEmpty()) {
return
} else {
// Do your work here
}
}
而在你的活动课上这样做。
registerViewModel.validateSignupScreen()