Skip to content

Instantly share code, notes, and snippets.

@mformetal
Created April 5, 2016 01:47
Show Gist options
  • Select an option

  • Save mformetal/7c41bd6bfb7117c56d93cb31a29c1f94 to your computer and use it in GitHub Desktop.

Select an option

Save mformetal/7c41bd6bfb7117c56d93cb31a29c1f94 to your computer and use it in GitHub Desktop.
Base-Handling class for Fragments. Yes, I hate casting this much.
public abstract class BaseFragment extends Fragment {
@Override
public void onAttach(Context context) {
super.onAttach(context);
((MainApp) context.getApplicationContext()).getApplicationComponent().inject(this);
Map<Object, Class> map = getCastMap();
for (Object object: map.keySet()) {
Class clazz = map.get(object);
Object cast = clazz.cast(context);
String objectTypeName = clazz.getName();
for (Field field: getClass().getDeclaredFields()) {
String fieldTypeName = field.getType().getName();
if (Objects.equals(fieldTypeName, objectTypeName)) {
if (!field.isAccessible()) {
field.setAccessible(true);
}
try {
field.set(this, cast);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
@Override
public void onDetach() {
super.onDetach();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Icepick.restoreInstanceState(this, savedInstanceState);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Icepick.saveInstanceState(this, outState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(getLayoutId(), container, false);
ButterKnife.bind(this, view);
return view;
}
protected abstract Map<Object, Class> getCastMap();
protected abstract int getLayoutId();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment