Skip to content

Instantly share code, notes, and snippets.

@StevenRudenko
Created June 8, 2015 17:53
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save StevenRudenko/a1dd6d76a3f2afed94dc to your computer and use it in GitHub Desktop.
Save StevenRudenko/a1dd6d76a3f2afed94dc to your computer and use it in GitHub Desktop.
import android.app.Activity;
import android.app.Dialog;
import android.support.v4.app.DialogFragment;
/**
* Base dialog fragment.
* @param <Listener> listener type.
*/
public abstract class BaseDialogFragment<Listener> extends DialogFragment {
/** Dialog listener instance. */
private Listener listener;
/**
* Provides listener class to cast listener.
* @return listener class.
*/
protected Class<Listener> getListenerClass() {
return null;
}
public Listener getListener() {
return listener;
}
/**
* Indicates whether listener is optional.
* @return true if listener is optional.
*/
protected boolean isListenerOptional() {
return getListenerClass() == null;
}
@SuppressWarnings("unchecked")
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
final Class<Listener> clazz = getListenerClass();
if (clazz == null) {
listener = null;
} else if (getParentFragment() != null
&& clazz.isAssignableFrom(getParentFragment().getClass())) {
listener = (Listener) getParentFragment();
} else if (clazz.isAssignableFrom(activity.getClass())) {
listener = (Listener) activity;
} else {
listener = null;
}
if (listener == null && !isListenerOptional()) {
throw new ClassCastException(activity.getClass().getName() + " must implement listener");
}
}
public boolean isShowing() {
final Dialog dialog = getDialog();
return dialog != null && dialog.isShowing();
}
// Hack for android issue 17423 in the compatibility library
@Override
public void onDestroyView() {
if (getDialog() != null && getRetainInstance()) {
getDialog().setDismissMessage(null);
}
super.onDestroyView();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment