我想验证使用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上的错误一起使用
RegisterErrors :
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
无效,我也不知道该怎么办..请帮助我,:)
答案 0 :(得分:0)
您可以在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()