Fragment替换工具类

package com.***.***.utils;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;


/**
 * Created by Jin_ on 2015/9/23.
 */
public class FragmentTransform {

    /**
     * 带Bundle参数传值替换
     * @param fragmentManager
     * @param fragment          替换的Fragment
     * @param addToBackStack    是否加入堆栈
     * @param containerId       替换布局id
     * @param bundle            bundle参数
     */
    public static void addFragmentWithBundle(FragmentManager fragmentManager, Fragment fragment, boolean addToBackStack, int containerId, Bundle bundle) {

        if (null != bundle){
            fragment.setArguments(bundle);
        }

        String backStackName = fragment.getClass().getName();
        boolean fragmentPopped = fragmentManager.popBackStackImmediate(backStackName, 0);
        if (!fragmentPopped) {
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            if (addToBackStack)
                transaction.addToBackStack(backStackName);
            transaction.replace(containerId,fragment,backStackName);
            transaction.commit();
        }
    }

    /**
     * 不带Bundle参数
     * @param fragmentManager
     * @param fragment
     * @param addToBackStack
     * @param containerId
     */
    public static void addFragment(FragmentManager fragmentManager,Fragment fragment, boolean addToBackStack, int containerId) {
        addFragmentWithBundle(fragmentManager, fragment, addToBackStack, containerId, null);
    }

    /**
     * remove
     * @param context
     * @param fragmentManager
     */
    public static void removeFragment(Context context,FragmentManager fragmentManager){
        if (null == fragmentManager) {
            fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
        }
        fragmentManager.popBackStack();
    }
}

你可能感兴趣的:(Fragment替换工具类)