Skip to content

Instantly share code, notes, and snippets.

@juliomarcos
Last active August 29, 2015 14:04
Show Gist options
  • Save juliomarcos/f50a6bb39ad541f3f2cf to your computer and use it in GitHub Desktop.
Save juliomarcos/f50a6bb39ad541f3f2cf to your computer and use it in GitHub Desktop.
DRY way to manage fragments
static Map<String, Class<?>> fragmentsClassMap;
static {
fragmentsClassMap = new HashMap<String, Class<?>>();
Class<?>[] fragmentClassArray = new Class<?>[] {
Fragment1.class,
Fragment2.class
};
for (Class<?> clazz : fragmentClassArray) {
fragmentsClassMap.put(clazz.getName(), clazz);
}
}
public void switchFragment(String fragmentName) {
switchFragment(fragmentName, null);
}
public void switchFragment(String fragmentName, Bundle argsBundle) {
Class<?> clazz = fragmentsClassMap.get(fragmentName);
try {
Fragment newFragment = (Fragment) clazz.newInstance();
if (argsBundle != null) {
newFragment.setArguments(argsBundle);
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, newFragment)
.addToBackStack(fragmentName)
.commit();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment