Android-工作遭遇-Fragment管理篇
阿新 • • 發佈:2018-12-11
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<Fragment> 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(); } }