MVP架構:
activity_login:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="evan.chen.app.mvp_pattern.LoginActivity">
<EditText
android:id="@+id/login_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="Login Id" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="Password" />
<Button
android:id="@+id/logn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Login" />
<TextView
android:id="@+id/login_result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</LinearLayout>
LoginActivty(View):
public class LoginActivity extends AppCompatActivity implements LoginContract.ILoginView {
private LoginPresenter presenter;
private Button loginButton;
private EditText loginId;
private EditText password;
private TextView loginResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
presenter = new LoginPresenter(this);
this.loginButton = (Button) this.findViewById(R.id.logn);
this.loginId = (EditText) findViewById(R.id.login_id);
this.password = (EditText) findViewById(R.id.password);
this.loginResult = (TextView) findViewById(R.id.login_result);
this.loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
presenter.login(loginId.getText().toString(), password.getText().toString());
}
});
}
@Override
public void onLoginSuccess(String message) {
this.loginResult.setText(message);
}
@Override
public void onLoginFail(String message) {
this.loginResult.setText(message);
this.password.setText("");
}
}
LoginContract:
public interface LoginContract {
interface ILoginView {
void onLoginSuccess(String message);
void onLoginFail(String message);
}
interface ILoginPresenter {
void login(String id, String password);
}
}
LoginPresenter(Presenter):
public class LoginPresenter implements LoginContract.ILoginPresenter{
private LoginContract.ILoginView view;
LoginPresenter(LoginContract.ILoginView view) {
this.view = view;
}
@Override
public void login(String id, String password) {
User user = new User();
boolean isSuccess = user.login(id, password);
if (isSuccess) {
view.onLoginSuccess("Incorrect username or password.");
} else {
view.onLoginFail("Login success");
}
}
}
User(Model):
public class User {
public boolean login(String id, String password) {
if ( id.equals("abc") && password.equals("123")) {
return true;
} else {
return false;
}
}
}
謝謝大家願意花時間閱讀,小弟弟我在此鞠躬