- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在关注 this tutorial将 Dagger 2 添加到我的 Android 项目。
完成设置并创建模块和组件后,我可以像这样在 Activity 中添加依赖项:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
ButterKnife.bind(this);
((AppController) getApplication()).getNetComponent().inject(this);
}
我正在纠结于如何在 Fragment 和 IntentService 中注入(inject)依赖项?
public class FragmentBrandList extends ListFragment {
}
在这个类中,我应该在哪个@Override
方法中请求注入(inject),它的代码是什么?
最佳答案
In this class which @Override method i should use and what will be the code to add dependency in fragment?
在 Fragment 中调用注入(inject)的正确位置是 onAttach(Context context)
。这在 Dagger 2 用户指南的注入(inject)位置部分有说明here
@Override
public void onAttach(Context context) {
((AppController) context.getApplicationContext()).getNetComponent().inject(this);
super.onAttach(context);
}
在服务中调用注入(inject)的正确位置是onCreate()
@Override
public void onCreate() {
((AppController) getApplication()).getNetComponent().inject(this);
super.onCreate();
}
请注意,在这两种情况下,注入(inject)请求都出现在调用 super.onCreate()
之前。 Dagger 用户指南是这样解释的:
It is crucial to call AndroidInjection.inject() before super.onCreate() in an Activity, since the call to super attaches Fragments from the previous activity instance during configuration change, which in turn injects the Fragments. In order for the Fragment injection to succeed, the Activity must already be injected. For users of ErrorProne, it is a compiler error to call AndroidInjection.inject() after super.onCreate().
换句话说:
super.onCreate()
调用重新附加来自先前实例的 fragment super
调用导致 fragment 被重新注入(inject)(因为 fragment 是在 onAttach
中注入(inject)的)super.onCreate()
之前请求在你的 Activity 中注入(inject)。您始终可以通过查看 com.google.dagger:dagger-android
类(如 DaggerFragment
和 DaggerService)的相关源代码来检查注入(inject)位置
。参见 the GitHub repo here
对于您的具体示例,请确保您已将新的注入(inject)站点添加到 NetComponent:
void inject(FragmentBrandList frag);
void inject(BrandListService service);
关于java - 如何在 Android fragment 和服务中请求注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41303896/
我是一名优秀的程序员,十分优秀!