Android Architecture — onActivityResult 是誰的職責?View? Presenter?

YANBIN HUNG
Jun 15, 2018 · 12 min read

一切從MVP 開始…

MVP 的互動行為

Android 如何套用?

所以問題是什麼?

<com.facebook.login.widget.LoginButton
android:id="@+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp" />
callbackManager = CallbackManager.Factory.create();LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
// App code
}
@Override
public void onCancel() {
// App code
}
@Override
public void onError(FacebookException exception) {
// App code
}
});
//全部都要自己再定義一次
interface FBLoginManager {
void registerCallback(LoginCallback callback);
}
interface LoginCallback {
...
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}

解法ㄧ:一路往下傳

interface LoginContract.Presenter {

...
void onActivityResult(int requestCode, int resultCode, Intent data);
}
interface FBLoginManager {
void registerCallback(LoginCallback callback);
void onActivityResult(int requestCode, int resultCode, Intent data);
}

錯了,全部都錯了

解法二:讓 MVP “活”起來

//把FB相關字眼拿掉了,如果之後有想要整合google login可以不用多一個新的介面
interface LoginService{
void registerCallback(LoginCallback callback);
}
interface LoginCallback{
...
}
class MainActivity implements LoginContract.View, LoginService {    //facebook 相關全部都放在 MainActivity 裡面
private CallbackManager callbackManager = CallbackManager.Factory.create();
@Override
public void registerCallback(LoginCallback callback) {
...
}
//其他有關 View 的實作
...
//可以放心的使用 onActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
}
class LoginPresenterImp implements LoginContract.Presenter {    public LoginPresenterImp(LoginContract.View view, LoginService service) {
this.view = view;
this.service = service;
}
//其他實作
...
}
class MainActivity implements LoginContract.View, LoginService { ...
private LoginPresenter presenter;
@Override
public void onCreate(Bundle savedInstanceState) {
presenter = LoginPresenterImp(this, this);
...
}
...}

廣義MVP

總結

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade