java - MVVM 数据绑定验证
问题描述
我想使用 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>
问题是..我想在单击提交按钮后验证用户输入..如何在视图模型上通过绑定验证它
我试试这个:
视图模型:
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
}
}
在您的 Activity 类中执行以下操作:
registerViewModel.validateSignupScreen()
推荐阅读
- sql - RedShift 并行运行多个查询
- arrays - 从对象数组中选择特定索引
- javascript - 使用 css 动画检测太空入侵者的位置
- python - 如何从python加载动态库定义的外部整数
- tfs - 如何在 TFS 2018 的 sprint 级别更改任务板上的列名称?
- botframework - 附加 Skype 联系人 Microsoft Bot 框架
- javascript - Angular - 创建 JSON 对象以存储与每个路由关联的数据
- c# - 并行访问文件
- hive - 在 Hive 中将列名转换为行
- javascript - 如何在 NetSuite 上查找销售订单中的相关记录?