Created
November 24, 2017 09:51
-
-
Save rayworks/d257306eb5f6d6b14a752d217984b107 to your computer and use it in GitHub Desktop.
Reset the view when applying MVP pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Returns the view configured in the presenter which real implementation is an Activity or | |
* Fragment using this presenter. | |
*/ | |
public final T getView() { | |
return view; | |
} | |
/** | |
* Configures the View instance used in this presenter as view. | |
*/ | |
public void setView(T view) { | |
this.view = view; | |
} | |
/** | |
* Changes the current view instance with a dynamic proxy to avoid real UI updates. | |
*/ | |
void resetView() { | |
final Class<?> viewClass = getViewInterfaceClass(); | |
InvocationHandler emptyHandler = new InvocationHandler() { | |
@Override | |
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { | |
return null; | |
} | |
}; | |
ClassLoader classLoader = viewClass.getClassLoader(); | |
Class[] interfaces = new Class[1]; | |
interfaces[0] = viewClass; | |
this.view = (T) Proxy.newProxyInstance(classLoader, interfaces, emptyHandler); | |
} | |
private Class<?> getViewInterfaceClass() { | |
Class<?> interfaceClass = null; | |
Class<?>[] interfaces = this.view.getClass().getInterfaces(); | |
for (int i = 0; i < interfaces.length; i++) { | |
Class<?> interfaceCandidate = interfaces[i]; | |
if (RosiePresenter.View.class.isAssignableFrom(interfaceCandidate)) { | |
interfaceClass = interfaceCandidate; | |
} | |
} | |
return interfaceClass; | |
} | |
/** | |
* Represents the View component inside the Model View Presenter pattern. This interface must be | |
* used as base interface for every View interface declared. | |
*/ | |
public interface View { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment