自Android支持庫的版本25.2.0以來,類FragmentManager.FragmentLifecycleCallbacks
是靜態的並且可供所有人訪問。
我們現在可以使用該類的一個實例並將其註冊到Activity
的supportFragmentManager
中。
public class ExampleActivity extends AppCompatActivity {
public void onCreate(Bundle savedInstaceState) {
// initialization code
getSupportFragmentManager()
.registerFragmentLifecycleCallbacks(new FragmentManager.FragmentLifecycleCallbacks() {
@Override
public void onFragmentPreAttached(FragmentManager fm, Fragment f, Context context) {
super.onFragmentPreAttached(fm, f, context);
}
@Override
public void onFragmentAttached(FragmentManager fm, Fragment f, Context context) {
super.onFragmentAttached(fm, f, context);
}
@Override
public void onFragmentCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) {
super.onFragmentCreated(fm, f, savedInstanceState);
}
@Override
public void onFragmentActivityCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) {
super.onFragmentActivityCreated(fm, f, savedInstanceState);
}
@Override
public void onFragmentViewCreated(FragmentManager fm, Fragment f, View v, Bundle savedInstanceState) {
super.onFragmentViewCreated(fm, f, v, savedInstanceState);
}
@Override
public void onFragmentStarted(FragmentManager fm, Fragment f) {
super.onFragmentStarted(fm, f);
}
@Override
public void onFragmentResumed(FragmentManager fm, Fragment f) {
super.onFragmentResumed(fm, f);
}
@Override
public void onFragmentPaused(FragmentManager fm, Fragment f) {
super.onFragmentPaused(fm, f);
}
@Override
public void onFragmentStopped(FragmentManager fm, Fragment f) {
super.onFragmentStopped(fm, f);
}
@Override
public void onFragmentSaveInstanceState(FragmentManager fm, Fragment f, Bundle outState) {
super.onFragmentSaveInstanceState(fm, f, outState);
}
@Override
public void onFragmentViewDestroyed(FragmentManager fm, Fragment f) {
super.onFragmentViewDestroyed(fm, f);
}
@Override
public void onFragmentDestroyed(FragmentManager fm, Fragment f) {
super.onFragmentDestroyed(fm, f);
}
@Override
public void onFragmentDetached(FragmentManager fm, Fragment f) {
super.onFragmentDetached(fm, f);
}
}, true);
}
}
25.2.0以前的版本的任何解決方案? –
不是我所知道的。您可以使用「BaseFragment」方法來模擬它,與此相比,它非常有限。我已經看到有更多的「神祕」方式的人喜歡有線程傾聽事件,但沒有測試過,不會推薦它。現在只是更新支持庫的問題 – Olinasc