我正在使用MVVM 设计模式制作用户登录屏幕,但当它实现电话号码验证逻辑时,我陷入了困境。我读出了使用 mvvm 时要遵循的规则 (规则 4),即视图中不应该有任何逻辑,甚至不应该是简单的 if 条件。视图的所有逻辑都发生在 ViewModel 中。
这是我的 ViewModel 类。
public class LoginViewModel extends AndroidViewModel {
private LoginRepository loginRepository;
private HashMap<String,String> mNumberParam;
private MutableLiveData<Boolean> isValidated;
public LoginViewModel(@NonNull Application application) {
super(application);
loginRepository=LoginRepository.getInstance();
isValidated=new MutableLiveData<>();
}
public LiveData<List<OtpEnterModel.Data>> enterNumberApiHit(){
return loginRepository.enterNumberApiHit(mNumberParam);
}
public void onSubmitClick(String number){
//if mobile number not enter or wrong enter show message ,and tell the view to hide other view
if (number==null) {
Toast.makeText(getApplication(), "Invalid mobile number", Toast.LENGTH_SHORT).show();
isValidated.setValue(false);
} else {
//otherwise save mobile number in hashMap ,and tell the view to work further
isValidated.setValue(true);
saveNumberParam(number);
}
}
//to save the mobile number in hashMap with key i.e mobile_number.
private void saveNumberParam(String mobileNumber) {
//if hashMap null then initialize it
if (mNumberParam ==null) {
mNumberParam = new HashMap<>();
}
mNumberParam.put(MyConstant.MOBILE_NUMBER, mobileNumber);
}
public LiveData<Boolean> isValidated(){
return isValidated;
}
}
天涯尽头无女友
相关分类