Skip to content

Instantly share code, notes, and snippets.

@philandrews100
Created August 14, 2017 15:38
Show Gist options
  • Save philandrews100/e73b63d278b6af1e74f91745a538cd12 to your computer and use it in GitHub Desktop.
Save philandrews100/e73b63d278b6af1e74f91745a538cd12 to your computer and use it in GitHub Desktop.
import android.app.Activity;
import android.content.Context;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.widget.FrameLayout;
/**
* Created by phil on 14/08/2017.
*/
public class FragmentController {
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
private Activity activity;
private Fragment currentFragment;
private FrameLayout flMainContainer;
public FragmentController(Context context, FrameLayout flContainer, FragmentManager fragmentManager) {
this.activity = (Activity) context;
flMainContainer = flContainer;
setupFragManager(fragmentManager);
}
public void switchFragment(Fragment fragment, String fragmentName) {
removeOldFragment();
addNewFragment(fragment, fragmentName);
}
public void addNewFragment(Fragment fragment, String fragmentName) {
fragmentTransaction = getFragManager().beginTransaction();
currentFragment = fragment;
fragmentTransaction.replace(flMainContainer.getId(), currentFragment, fragmentName);
fragmentTransaction.addToBackStack(fragmentName);
fragmentTransaction.commitAllowingStateLoss();
}
public void popBackStack() {
fragmentManager.popBackStack();
}
private void removeOldFragment() {
fragmentTransaction = getFragManager().beginTransaction();
if (currentFragment != null) {
if (this.activity != null) {
fragmentTransaction.remove(currentFragment);
getFragManager().popBackStack();
fragmentTransaction.commitAllowingStateLoss();
}
}
}
private android.support.v4.app.FragmentManager getFragManager() {
if (fragmentManager == null) {
throw new IllegalStateException(FragmentController.class.getSimpleName() +
" is not initialized, call setupFragmentManager(...) first");
}
return fragmentManager;
}
private void setupFragManager(FragmentManager fragmentManager) {
this.fragmentManager = fragmentManager;
}
public int getBackstackCount() {
return fragmentManager.getBackStackEntryCount();
}
public Fragment getCurrentFragment() {
return this.currentFragment;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment