Skip to content

Instantly share code, notes, and snippets.

@SelvinPL
Last active August 29, 2015 14:17
Show Gist options
  • Save SelvinPL/5003577e7bd8b4f67de9 to your computer and use it in GitHub Desktop.
Save SelvinPL/5003577e7bd8b4f67de9 to your computer and use it in GitHub Desktop.
interface IMySuperInterface {
void setNumPlats(int numero);
}
class MyAtivity extends Activity implements IMySuperInterface {
//do the implentation and other stuff;
}
class MyFragment extends Fragment {
IMySuperInterface defaultInstance = new IMySuperInterface {
public setNumPlats(int numero) {
Log.e("MyFragment", "IMySuperInterface.setNumPlats() was called without Activity attached!");
//or throw ... depends on your needs
}
}
IMySuperInterface theInterfaceInstance = defaultInstance;
void onAttach(Activity activty) {
if(activty instanceof IMySuperInterface){
theInterface = (IMySuperInterface)activty;
return;
}
//you can also leave the defaultInstance but then setNumPlats will not do anything
//better throw this error it will be easy to cach it in tests
throw new RuntimeException("This fragment needs Activity that implements IMySuperInterface");
}
void onDettach() {
//set it back to default instance to avoid NPE
theInterface = defaultInstance;
}
void SomrMethodWhereIWanaUseIt(){
theInterfaceInstance.setNumPlats(0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment