Skip to content

Instantly share code, notes, and snippets.

@vkolev
Forked from JoseBueno/FragmentLoader.java
Created October 6, 2015 10:09
Show Gist options
  • Save vkolev/2f07624722eed1701f03 to your computer and use it in GitHub Desktop.
Save vkolev/2f07624722eed1701f03 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 - taskInstallationServiceFragment = (TaskInstallationServiceFragment)
* FragmentLoader.addFragment(TaskInstallationServiceFragment.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();
} 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