【发布时间】:2013-11-10 15:27:14
【问题描述】:
我正在使用 Otto 事件总线订阅 ListFragment 中的某些事件。总线实例是在 Application 的子类中存储和创建的,换句话说,它总线应该作为一个单例工作。好像不是这样的……
片段在onActivityCreated(Bundle) 中注册到总线并在onDestroy() 中取消注册。这不能正常工作。我从调用unregister() (java.lang.IllegalArgumentException: Missing event handler for an annotated method...) 时应用程序崩溃的设备收到了几份崩溃报告。只有在调用任何 register() 之前调用 unregister() 或调用两次 unregister() 时才会引发此异常。这可能只发生在......
-
onActivityCreated(Bundle)不会在onDestroy()之前调用。 -
onDestroy()被调用了两次。 -
Application实例在调用onActivityCreated(Bundle)和onDestroy()之间重新创建。
我的应用类:
public class App extends Application {
private static App sInstance;
private Bus bus;
public static App getInstance() {
return sInstance;
}
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
bus = new Bus(ThreadEnforcer.ANY);
}
public Bus getEventBus() {
return bus;
}
}
片段类:
public class MyFragment extends ListFragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
App.getInstance().getEventBus().register(this);
}
@Subscribe
public void onEvent(MyEvent event) {
....
}
@Override
public void onDestroy() {
App.getInstance().getEventBus().unregister(this);
super.onDestroy();
}
}
更新:
我遗漏了一个重要的细节;这些片段用于ViewPager。当用户在ViewPager 中的页面之间滑动时,它们会按需实例化。这个小细节似乎改变了某些设备上的片段生命周期:onActivityCreated() 在创建ViewPager 之后启动的片段永远不会被调用。
【问题讨论】:
-
为什么不在
onCreate() / onDestroy()中调用它?他们配对了。
标签: android android-fragments activity-lifecycle otto fragment-lifecycle