Skip to content

Instantly share code, notes, and snippets.

@JakeWharton
Created May 6, 2012 09:12
Show Gist options
  • Save JakeWharton/2621173 to your computer and use it in GitHub Desktop.
Save JakeWharton/2621173 to your computer and use it in GitHub Desktop.
Base fragment to ensure the parent activity implements a contract interface.
/* Base fragment to ensure the parent activity implements a contract interface. */
public abstract class ContractFragment<T> extends Fragment {
private T mContract;
@Override
public void onAttach(Activity activity) {
try {
mContract = (T)activity;
} catch (ClassCastException e) {
throw new IllegalStateException(activity.getClass().getSimpleName()
+ " does not implement " + getClass().getSimpleName() + "'s contract interface.", e);
}
super.onAttach(activity);
}
@Override
public void onDetach() {
super.onDetach();
mContract = null;
}
public final T getContract() {
return mContract;
}
}
/* Example fragment showing usage of ContractFragment. */
public class MyCoolFragment extends ContractFragment<MyCoolFragment.Contract> {
public interface Contract {
void sayHi(String message);
}
public void somethingHappened() {
getContract().sayHi("Hi, Mom!");
}
}
@kaciula
Copy link

kaciula commented Jan 15, 2014

Isn't it easier and more straightforward to use Otto? Could you comment on the use cases where to use this instead of an event bus?

@nyxee
Copy link

nyxee commented Sep 26, 2015

An example is in the EU4U sample code from The Busy Coder's Guide to Android Development
https://commonsware.com/Android

@umranabdullaoutware
Copy link

onAttach(Activity activity) is now deprecated in favour of onAttach(Context context). Does that impact this pattern? Especially considering the use of ContextWrapper.

@marksalpeter
Copy link

Hey guys! I use this concept so heavily that I packaged my base ContractFragmet and ContractDialogFragment implementations into a small library. I also extended this pattern to support parent fragment implementations of the contract as well. You can find instructions on how to add this in gradle here:

https://github.com/marksalpeter/contract-fragment

Let me know what you think :)

@rpattabi
Copy link

Shocked to see mContract in @JakeWharton's code. I thought he is totally against Hungarian notation..

Oh I see, that was 7 years ago. Forgivable! :--)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment