Skip to content

Instantly share code, notes, and snippets.

@jmarkovic
Last active August 30, 2016 12:21
Show Gist options
  • Save jmarkovic/6fa3c42b95ec6f32a8ed2798f59e490e to your computer and use it in GitHub Desktop.
Save jmarkovic/6fa3c42b95ec6f32a8ed2798f59e490e to your computer and use it in GitHub Desktop.
An Android Studio (and IDEA) file template that generates a Fragment with all the boilerplate: TAG (with a String literal), newInstance() factory method with arguments Bundle, check for bundle in onCreate, check and attach the Callback in onAttach, attach STUB callback in onDetach and the implementation of a STUB.
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
#parse("File Header.java")
public class ${NAME} extends Fragment {
public static final String TAG = "${NAME}";
public static ${NAME} newInstance() {
${NAME} fragment = new ${NAME}();
Bundle bundle = new Bundle();
// add arguments to bundle
fragment.setArguments(bundle);
return fragment;
}
interface Callbacks {
Callbacks STUB = new Callbacks() { };
}
private Callbacks callbacks = Callbacks.STUB;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() == null) {
throw new UnsupportedOperationException("Fragment must be instantiated using newInstance() method.");
}
}
@Override
public void onAttach(Context context) {
if (context instanceof Callbacks) {
super.onAttach(context);
this.callbacks = (Callbacks) context;
} else {
throw new IllegalArgumentException(String.format(
"%s must implement %s", context.getClass().getSimpleName(), Callbacks.class.getSimpleName()
));
}
}
@Override
public void onDetach() {
super.onDetach();
this.callbacks = Callbacks.STUB;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment