我正在开发一个使用NavigationDrawer的应用程序。Different fragments are placed into the content view of the MainActivitywhenever a menu item in the drawer is selected. 要通知已MainActivity成功Fragment附加,将执行以下回调:
public class CustomFragment extends Fragment {
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached();
}
}
由于我开始在项目中使用Otto和Dagger,我很好奇如何用.post()事件替换回调,例如:
mBus.post(new CustomFragmentAttachedEvent);
问题mBus是null在onAttach(). 它在onCreate().
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MyApp) getActivity().getApplication()).getObjectGraph().inject(this);
}
参考:
您可以自己轻松地试用该示例:从NavigationDrawerAndroid Studio 中可用的模板创建一个新项目,添加Dagger和Otto并尝试替换提到的回调。
工作解决方案:
- 这是最终工作版本中的示例片段。