add Fragment In Stack - Android User Interface

Android examples for User Interface:Fragment

Description

add Fragment In Stack

Demo Code


//package com.java2s;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentManager;

public class Main {
    public static int addFragmentInStack(FragmentManager fragmentManager,
            Fragment addFragment, Integer containerViewId) {

        int result = -1;

        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();/*from  ww w.  j a v  a 2 s. co  m*/
        Fragment currentFragment = getHigherFragmentInStack(fragmentManager);

        if (currentFragment != null) {

            fragmentTransaction.hide(currentFragment);

            final String currentOperationTag = addFragment.getClass()
                    .getName();

            if (containerViewId != null) {

                fragmentTransaction.add(containerViewId, addFragment,
                        currentOperationTag);
            } else {
                fragmentTransaction.add(addFragment, currentOperationTag);
            }
            fragmentTransaction.addToBackStack(currentOperationTag);
            result = fragmentTransaction.commit();
        }
        return result;
    }

    public static Fragment getHigherFragmentInStack(
            FragmentManager fragmentManager) {

        Fragment currentHigherFragment = null;
        int countFragment = fragmentManager.getBackStackEntryCount();

        if (countFragment > 0) {
            final String tag = fragmentManager.getBackStackEntryAt(
                    countFragment - 1).getName();
            currentHigherFragment = fragmentManager.findFragmentByTag(tag);

            Fragment childFragment = getHigherFragmentInStack(currentHigherFragment
                    .getChildFragmentManager());

            if (childFragment != null) {
                currentHigherFragment = childFragment;
            }

        }

        return currentHigherFragment;
    }
}

Related Tutorials