- Glide 的解耦方式很独特。
- 相关文章:Fragment 如何跟Activity的生命周期进行绑定
- 1.1 Glide.with()
|
|
|
|
|
|
- 1.2 这里主要看 RequestManagerFragment
|
|
1.3 绑定 RequestManagerFragment 至 FragmentManager,当前RequestManagerFragment已经有了其生命周期,看下如何实现
1234567891011121314151617181920@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)RequestManagerFragment getRequestManagerFragment(final android.app.FragmentManager fm, android.app.Fragment parentHint) {//a.根据TAG id获取RequestManagerFragment实例RequestManagerFragment current = (RequestManagerFragment) fm.findFragmentByTag(FRAGMENT_TAG);if (current == null) {// b. 如果a没获取实例,从内存的map内获取current = pendingRequestManagerFragments.get(fm);if (current == null) {// c. 以上a,b 都没有获取实例,则最后new一个,并put 到内存 map内current = new RequestManagerFragment();current.setParentFragmentHint(parentHint);pendingRequestManagerFragments.put(fm, current);// fragment 与 FragmentManager 绑定,那么 RequestManagerFragment 有了生命周期fm.beginTransaction().add(current, FRAGMENT_TAG).commitAllowingStateLoss();handler.obtainMessage(ID_REMOVE_FRAGMENT_MANAGER, fm).sendToTarget();}}return current;}1.4 以上步骤中参考 1.2中b操作使得RequestManagerFragment中有RequestManager,RequestManager在构造中将自身添加到Lifecycle中
|
|
- 2.1 Fragment 生命周期的传递
|
|
- 2.2 回调所有生命周期的接口
- RequestManagerFragment 下回调所有注册的 RequestManager 1234567891011121314151617181920212223242526@Overridepublic void removeListener(LifecycleListener listener) {lifecycleListeners.remove(listener);}void onStart() {isStarted = true;for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {lifecycleListener.onStart();}}void onStop() {isStarted = false;for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {lifecycleListener.onStop();}}void onDestroy() {isDestroyed = true;for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {lifecycleListener.onDestroy();}}}
- RequestManagerFragment 下回调所有注册的 RequestManager
总结
- 1.通过获取 Activity 的FragmentManager,绑定一个空RequestManagerFragment,以同步Activity生命周期
- 2.RequestManagerFragment 中初始化LifecycleListener
- 3.初始化RequestManagerFragment,同事初始化RequestManager,并注册至LifecycleListener
- 4.Activity 触发生命周期时,回调 Fragment,并透传至LifecycleListener,LifecycleListener会回调所有向其注册过的RequestManager
- 综上所得解耦新技能。奉上时序图