MVVM登录Demo

Model:

public static void getLoginResult(String username, String password, final LoginCallback callback){
        LoginApi api = getRetrofit().create(LoginApi.class);
        api.getLoginResult(username, password).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                loginResultObservableArrayList.add(response.body());
                call.cancel();
                callback.showSuccess();
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                call.cancel();
                callback.showError();
            }
        });
    }

ViewModel:

public void login(){
        if(LoginModel.loginResultObservableArrayList.size()>0){
            LoginModel.loginResultObservableArrayList.clear();
        }

        LoginModel.getLoginResult(mPhone.get(), mPwd.get(), new LoginCallback() {
            @Override
            public void showSuccess() {
                ObservableArrayList observableArrayList=LoginModel.loginResultObservableArrayList;
                if (observableArrayList.get(0).getErrorCode()==0){
                    Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(context, observableArrayList.get(0).getErrorMsg(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void showError() {
                Toast.makeText(context, "可能网络不畅通哦!", Toast.LENGTH_SHORT).show();
            }
        });
    }

View:

//View和ViewModel进行绑定:
mLoginViewModel=new LoginViewModel(this);
mainBinding.setLoginViewModel(mLoginViewModel);
//登录:
mainBinding.btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String phone=mainBinding.etPhone.getText().toString();
            String pwd=mainBinding.etPwd.getText().toString();

            if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(pwd) ){
                Toast.makeText(MainActivity.this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            mLoginViewModel.setData(phone,pwd);
            mLoginViewModel.login();
        }
    });

你可能感兴趣的:(MVVM登录Demo)