Skip to content

Instantly share code, notes, and snippets.

@JoseBueno
Last active October 6, 2015 16:56
Show Gist options
  • Save JoseBueno/73ba21bf952ff75a18ba to your computer and use it in GitHub Desktop.
Save JoseBueno/73ba21bf952ff75a18ba to your computer and use it in GitHub Desktop.
This is a simplified Android fragment loader that helps cut down on boilerplate in your apps.
package com.buenocodigo.utilities;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* Have fun using this, attribution is not necessary and I'm obviously not
* taking responsibility if this is used in a device to take over the world.
*
* example usage - serviceFragment = (serviceFragment)
* FragmentLoader.addFragment(ServiceFragment.class, this);
* Created by jbueno on 9/8/2015.
*/
public class FragmentLoader {
public static Fragment addFragment(Class fragmentType, Activity activity) {
return addFragment(fragmentType, activity, fragmentType.getName());
}
public static Fragment addFragment(Class fragmentType, Activity context, String tag){
return addFragment(fragmentType, context, tag, null);
}
public static Fragment addFragment(Class fragmentType, Activity context, Bundle args){
return addFragment(fragmentType, context, fragmentType.getName(), args);
}
public static Fragment addFragment(Class fragmentType, Activity context, String tag, Bundle args) {
FragmentManager fm = context.getFragmentManager();
Fragment fragment = fm.findFragmentByTag(tag);
if (fragment == null){
try{
Constructor<?> ctor = Class.forName(fragmentType.getName()).getConstructor();
fragment = (Fragment) ctor.newInstance();
if (args != null){
fragment.setArguments(args);
}
fm.beginTransaction().add(fragment, tag).commit();
// can't collapse if statements prior to API 17
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return fragment;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment