说明
使用MVP设计模式进行解耦
View层
Activity,Fragment为view层的成员,负责初始化各种view组件,监听点击,滑动等各种事件,并调用Presenter处理实际的业务流程.
Presenter层
实际的逻辑处理者
Modle
实体Bean
LoginPresenter
public class LoginPresenter implements BasePresenter<LoginPresenter.MvpView> {
private MvpView mView;
private UserCache userCache;
@Inject
public LoginPresenter(UserCache userCache) {
this.userCache = userCache;
}
public void setView(MvpView view) {
mView = view;
}
public void initialize() {
List<User> users = userCache.getHistoryList();
mView.initAutoComplete(users);
autoLogin();
}
/**
* 自动登录
*/
private void autoLogin() {
User user = userCache.getCurrUser();
if (user != null) {
if ("游客".equals(user.getAccount())) {
return;
}
mView.loginSuccess();
}
}
public void login(String account, String password) {
User user = userCache.getUser(account);
if (user == null) {
user = new User();
}
user.setAccount(account);
user.setUserName(account);
userCache.setCurrUser(user);
mView.loginSuccess();
}
public interface MvpView extends BaseMvpView {
void loginSuccess();
void loginFailure();
void initAutoComplete(List<User> users);
}
}
LoginAcitivty
public class LoginActivity extends BaseActivity implements LoginPresenter.MvpView {
@Bind(R.id.viewRoot)
ResizeLayout viewRoot;
@Bind(R.id.editAccount)
AutoCompleteTextView editAccount;
@Bind(R.id.editPassword)
EditText editPassword;
@Bind(R.id.viewInputPane)
View viewInputPane;
@Bind(R.id.viewHeadPane)
View viewHeadPane;
@Inject
LoginPresenter loginPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
getActivityComponent().inject(this);
initKeyBordListener();
loginPresenter.setView(this);
loginPresenter.initialize();
}
/**
* 登录
*/
@OnClick(R.id.btnLogin)
void login() {
String account = editAccount.getText().toString();
String password = editPassword.getText().toString();
if (TextUtils.isEmpty(account)) {
Toast.makeText(this, "account null", Toast.LENGTH_SHORT).show();
return;
}
loginPresenter.login(account, password);
}
@Override
public void loginSuccess() {
Intent intent = new Intent(this, HomeActivity.class);
startActivity(intent);
finish();
}
@Override
public void loginFailure() {
}
@Override
public void initAutoComplete(List<User> users) {
String[] COUNTRIES = new String[users.size()];
for (int i = 0; i < users.size(); i++) {
COUNTRIES[i] = users.get(i).getAccount();
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_dropdown_item_1line, COUNTRIES);
editAccount.setAdapter(adapter);
editAccount.setThreshold(0);
editAccount.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println("onItemClick");
hideSoftInput();
}
});
}
@Override
public void showLoading(String title, String msg) {
}
@Override
public void hideLoading() {
}
@Override
public void showError(String message) {
}
}