MVP1(乞丐版)
阿新 • • 發佈:2018-12-15
MvpActivity
public class MvpActivity extends Activity implements View.OnClickListener, IView { EditText mEtName, mEtPw; LoginPresenter mLoginPresenter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mvp); initView(); //建立一個Presenter例項 initPresenter(); } /** * 繫結Presenter */ private void initPresenter() { //把view傳給presenter進行繫結 mLoginPresenter = new LoginPresenter(this); } private void initView() { mEtName = findViewById(R.id.et_name); mEtPw = findViewById(R.id.et_pw); mEtPw.invalidate(); findViewById(R.id.button_login).setOnClickListener(this); } @Override public void onClick(View view) { int id = view.getId(); switch (id) { case R.id.button_login: User user = new User(mEtName.getText().toString(), mEtPw.getText().toString()); //通過presenter的例項,呼叫presenter中的方法 mLoginPresenter.submit(user); break; default: break; } } /** * 在Activity結束的時候解綁Presenter */ @Override protected void onDestroy() { super.onDestroy(); mLoginPresenter.detachView(); } @Override public void success(Object data) { //接受到了結果,進行資料展示 Toast.makeText(this, "success", Toast.LENGTH_SHORT).show(); } @Override public void fail(String msg) { //接受到了結果,進行資料展示 Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); } }
LoginPresenter
public class LoginPresenter { /** * 持有view的例項 */ private IView mIView; public LoginPresenter(@NonNull IView iView) { mIView = iView; } public void submit(User user){ if(checkName(user.getName()) && checkPw(user.getPw())){ //進行網路請求 boolean loginResult = NetUtils.loginApi(user); //拿到結果後 if (loginResult){ //通過view的例項,把資料回撥給view mIView.success(""); }else{ //通過view的例項,把資料回撥給view mIView.fail("失敗"); } }else{ //通過view的例項,把資料回撥給view mIView.fail("使用者名稱密碼錯"); } } public void detachView(){ mIView = null; } private boolean checkName(String name){ return !TextUtils.isEmpty(name); } private boolean checkPw(String pw){ return (!TextUtils.isEmpty(pw) && pw.length()>=6); } }
IView
public interface IView<T> {
void success(T data);
void fail(String msg);
}
NetUtils網路請求資料
public class NetUtils { public static boolean loginApi(User user){ SystemClock.sleep(2000); if(user.getName().equals("dj") && user.getPw().equals("123456")){ //TODO:這裡最終需用真正的介面 return true; } return false; } }
User bean類
public class User {
private String name;
private String pw;
public User(String name, String pw) {
this.name = name;
this.pw = pw;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPw() {
return pw;
}
public void setPw(String pw) {
this.pw = pw;
}
}