Android-工作遭遇-Fragment管理篇

Fragment,简称碎片,是Android 3.0(API 11)提出的,为了兼容低版本,support-v4库中也开发了一套Fragment API,最低兼容Android 1.6。

过去support-v4库是一个jar包,24.2.0版本开始,将support-v4库模块化为多个jar包,包含:support-fragment, support-ui, support-media-compat等,这么做是为了减少APK包大小,你需要用哪个模块就引入哪个模块。

Fragment作为Android最基本,最重要的基础概念之一,在开发中经常会和他打交道。

我们开发的时候,经常会去加载fragment,有时候管理他,并且或者目前在最前的fragment是什么类型.以及调用方式..activity需要去检测fragment的活动轨迹等等


public class MyFragmentManager {
    private static List task = new ArrayList<>();
    private static MyFragmentManager sFragmentManager;
    private onFragmentChangeListener mOnFragmentChangeListener;

    private MyFragmentManager() {
    }

    public static MyFragmentManager getInstance() {
        if (sFragmentManager == null) {
            sFragmentManager = new MyFragmentManager();
        }
        return sFragmentManager;
    }

    // 这个方法是添加一个fragment.最好在base的oncreateview中添加
    public void pushOneFragment(Fragment f) {
        task.add(0, f);
        if (mOnFragmentChangeListener != null) {
            mOnFragmentChangeListener.onAdd();
        }
    }

    // 关闭fragment的时候,调用此方法进行销毁操作
    public void PopOneFragment(Fragment f) {
        if (task.contains(f)) {
            task.remove(f);
            f = null;
            if (mOnFragmentChangeListener != null) {
                mOnFragmentChangeListener.onPop();
            }
        }
    }

    // 跳转到某个fragment
    public void PopToStartFragment() {
        for (int i = 0; i < task.size(); i++) {
            Fragment mySupportFragment = task.get(i);
          
            if (mySupportFragment instanceof Start) {
                break;
            }else {
                // 这里是我自己写的关闭方法,也就是统一的fragment销毁方法.
                mySupportFragment.pop();
            }
        }
    }

    // 获取最顶层的fragment
    public Fragment getTopFragment() {
        Fragment mySupportFragment = null;
        if (task.size() != 0) {
            mySupportFragment = task.get(0);
        }
        return mySupportFragment;
    }

    public void onViewCreated(Fragment mySupportFragment) {
        if (mOnViewCratedListener!= null) {
            mOnViewCratedListener.onViewCreated(mySupportFragment);
        }
    }

    private onViewCratedListener mOnViewCratedListener;

    public void setOnViewCratedListener(onViewCratedListener onViewCratedListener) {
        mOnViewCratedListener = onViewCratedListener;
    }

    public interface onViewCratedListener{
        void onViewCreated(Fragment mySupportFragment);
    }



    public onFragmentChangeListener getOnFragmentChangeListener() {
        return mOnFragmentChangeListener;
    }

    public void setOnFragmentChangeListener(onFragmentChangeListener onFragmentChangeListener) {
        mOnFragmentChangeListener = onFragmentChangeListener;
    }

    public interface onFragmentChangeListener{

        void onAdd();
        void onPop();

    }

 

}

 

你可能感兴趣的:(android,Android开发)