我的组件就像
@GithubListActivityScope
@Component(modules = { GithubListActivityModule.class,GlideActivityModule.class })
public interface GithubListActivityComponent {
GithubUserListAdapter githubUserListAdapter ( );
RequestManager requestManager();
LinearLayoutManager linearLayoutManager();
}
我有一个这样的模块:
@Module
public class GithubListActivityModule {
private final Activity githubListActivity;
public GithubListActivityModule ( Activity activity ) {
this.githubListActivity = activity;
}
@Provides
@GithubListActivityScope
Activity activity ( ) {
return this.githubListActivity;
}
@Provides
@GithubListActivityScope
public LinearLayoutManager linearLayoutManager(Activity activity){
return new LinearLayoutManager ( activity );
}
}
问题: 我有兴趣像这样注入LinearLayout经理:
@GithubListActivityScope
@Inject
LinearLayoutManager linearLayoutManager;
虽然我的构件是这样构建的:
githubListActivityComponent = DaggerGithubListActivityComponent.builder ()
.githubListActivityModule ( new GithubListActivityModule ( this ) )
.build ();
我的线性布局管理器未实例化。但是当我手动做
时 linearLayoutManager = githubListActivityComponent.linearLayoutManager ();
工作正常。我哪里错了?
答案 0 :(得分:3)
我传递的所有地方Activity
,我应完全 相同的 类名称(不是其父级)所以一次将"Activity"
的每个参数和返回类型编辑为"GithubListActivity"
,然后添加
void inject( GithubListActivity activity);
在component class
然后注入"GithubListActivity"
像这样:
DaggerGithubListActivityComponent.builder ()
.githubListActivityModule ( new GithubListActivityModule ( this ) )
.build ().inject ( this );
然后代码对我有用..
课程:
1.定义注入方法并注入当前活动
<强> 2。在这种情况下使用完全相同类型的对象(不是父对象)使用“GithubListActivity”而不仅仅是活动。
答案 1 :(得分:1)
Dagger 2不会自动注入字段。它也不能注入私有字段。如果要使用字段注入,则必须在@Component接口中定义一个方法,该方法将要注入的实例作为参数(From - http://www.vogella.com/tutorials/Dagger/article.html#special-treatment-of-fields-in-dagger)
假设您有一个要注入这些依赖项的片段或Activity,那么就这样做 -
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((YouApplicationClass) getActivity().getApplication()).getmComponent().inject(this);
}
让你的Application类就像这样 -
public class YourApplicationClass extends MultiDexApplication {
private static final String TAG = v.class.getSimpleName();
private YourComponent mComponent;
@Override
public void onCreate() {
super.onCreate();
mComponent = DaggerYoutComponent.builder()
.yourModule(new YourModule(this))
.build();
}
public YourComponent getmComponent() {
return mComponent;
}
.... lots of other code
}
你的组件类就是这样 -
//@Singleton
@Component(modules = {YourModule.class})
public interface YourComponent {
void inject(Fragment yourFragment); //the parameter can be any class who is invoking this method i.e. Passing the reference to itself
..lots of other code
}