首先,我的解决方案FragmentManager.FragmentLifecycleCallbacks
包括
用于监听给定 FragmentManager 中发生的片段状态变化的回调接口
并坚持关注点的分离,我想说的是Android Architecture Blueprints中显示的方式。
Activity
创建Presenter
,传递View
/ Fragment
,这样
Presenter
知道它View
,而且把自己定为它的Presenter
在Activity
'sonCreate
我通过调用这个来注册一个FragmentLifecycleCallbacks
监听器
private void registerFragmentsLifecycleListener() {
// All registered callbacks will be automatically unregistered when
// this FragmentManager is destroyed.
getSupportFragmentManager.registerFragmentLifecycleCallbacks(
new FragmentManager.FragmentLifecycleCallbacks() {
// Called after the fragment has returned from its onActivityCreated
@Override
public void onFragmentActivityCreated(FragmentManager fm, Fragment f,
Bundle savedInstanceState) {
createPresenter(f);
}
}, false); // true to register callback for all child FragmentManagers
}
侦听器在Fragment
从其返回后会收到通知,onActivityCreated
以确保仅创建由a new添加的每个新 Fragment
实例。片段可以被附加/分离,它的视图可以被创建/销毁几次,不需要做任何事情,仍然得到它的.ViewPager
Presenter
Presenter
因为在娱乐的情况下(例如通过旋转),Fragment
s'在 sonCreate
之前被调用Activity
(FragmentLifecycleCallbacks
监听器注册的地方!),监听器无法实现onFragmentCreated
,它必须是onFragmentActivityCreated
。
对于给定的新Fragment
实例,我们可以确定Presenter
需要哪个:
private void createPresenter(Fragment fragment) {
if (fragment instanceof WhateverContract.View) {
WhateverContract.Presenter whateverPresenter =
new WhateverPresenter((WhateverContract.View) fragment);
} else if (...){}
}
与构造函数中的/Presenter
连接View
Fragment
private final WhateverContract.View mView;
public WhateverPresenter(@NonNull WhateverContract.View view) {
mView = checkNotNull(view, "view cannot be null!");
mView.setPresenter(this);
}
然后可以在Fragment
s中启动onResume
。
如果有什么问题或需要改进,请告诉我:)