Created
April 5, 2016 01:47
-
-
Save mformetal/7c41bd6bfb7117c56d93cb31a29c1f94 to your computer and use it in GitHub Desktop.
Base-Handling class for Fragments. Yes, I hate casting this much.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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