Last active
August 29, 2015 14:04
-
-
Save juliomarcos/f50a6bb39ad541f3f2cf to your computer and use it in GitHub Desktop.
DRY way to manage fragments
This file contains 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
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