1.model接口
public interface IUserMode {
/**
* 登录
*
* @param user
* @return 约定返回"true"为登录成功,其他为登录失败的错误信息
*/
String login(User user);
}
2.继承接口
public class UserMode implements IUserMode{
@Override
public String login(User user) {
boolean networkError = false; //网络是否异常
try {
Thread.sleep(3000);//模拟网络连接
if (networkError) {
return "网络异常";
} else if ("ethanco".equals(user.getUsername()) && "123456".equals(user.getPassword())) {
return "true";
} else {
return "账号或密码错误";
}
} catch (InterruptedException e) {
e.printStackTrace();
return e.getMessage();
}
}
}
3.view定义接口
public interface IUserView {
/**
* 登录成功
*/
void onLoginSuccess();
/**
* 登录失败
*
* @param error
*/
void onLoginFailed(String error);
}
4.继承接口
public class UserView implements IUserView {
@Override
public void onLoginSuccess() {
}
@Override
public void onLoginFailed(String error) {
}
}
5.p调用
public class UserPresenter {
private final IUserView userView;
private final UserMode userMode;
public UserPresenter(IUserView userView) {
this.userView = userView;
this.userMode =new UserMode();
}
public void login(final User user){
new Thread() {
@Override
public void run() {
final String res = userMode.login(user);
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if ("true".equals(res)) {
userView.onLoginSuccess();
} else {
userView.onLoginFailed(res);
}
}
});
}
}.start();
}
}
6.主方法继承使用
public class MainActivity extends AppCompatActivity implements IUserView, View.OnClickListener {
private UserPresenter userPresenter;
private EditText etUserName;
private EditText etPassword;
private ProgressDialog loginProgreess;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUserName = (EditText) findViewById(R.id.et_userName);
etPassword = (EditText) findViewById(R.id.et_password);
findViewById(R.id.btn_login).setOnClickListener(this);
userPresenter = new UserPresenter(this);
}
@Override
public void onLoginSuccess() {
loginProgreess.dismiss();
Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
}
@Override
public void onLoginFailed(String error) {
loginProgreess.dismiss();
Toast.makeText(getApplicationContext(), "登录失败:" + error, Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View view) {
String username = etUserName.getText().toString().trim();
String password = etPassword.getText().toString().trim();
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "账号或密码不能为空", Toast.LENGTH_SHORT).show();
return;
}
loginProgreess = ProgressDialog.show(this, "登录", "正在登录...");
userPresenter.login(new User(username, password));
}
}