我正在尝试将Dagger用作我的Android应用程序的依赖项注入库。在我的项目中,我在项目中有不同的Android模块,分别代表了不同的应用程序风格。我想使用依赖注入来允许每个模块定义自己的导航菜单。
我的MenuFragment类需要接口的一个实例(MenuAdapterGenerator):
public class MenuFragment extends Fragment {
@Inject
protected MenuAdapterGenerator generator;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//this.generator is always null here, though shouldn't it be injected already?:
BaseExpandableListAdapter adapter = new MenuAdapter(inflater, this.generator);
}
}
这是我的菜单模块的样子:
@Module (
injects = MenuAdapterGenerator.class
)
public class MenuDaggerModule {
public MenuDaggerModule() {
System.out.println("test");
}
@Provides @Singleton MenuAdapterGenerator provideMenuAdapterGenerator() {
return new MenuNavAdapterGenerator();
}
}
这是整个应用程序级别的模块(包括此MenuDaggerModule):
@Module (
includes = MenuDaggerModule.class,
complete = true
)
public class OverallAppModule {
}
(编辑:)这是我的MainActivity类,它创建对象图:
public class MainActivity extends Activity {
private ObjectGraph objGraph;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.objGraph = ObjectGraph.create(OverallAppModule.class);
this.mainWrapper = new MainWrapper(this, this.objGraph);
this.setContentView(R.layout.activity_main);
//Other instantiation logic
}
(编辑:)这是我实际制作MenuFragment的地方(在MainWrapper中):
public class MainWrapper {
public MainWrapper(Activity activity, ObjectGraph objGraph) {
this.menu = new MenuFragment();
this.objGraph.inject(this.menu);
//I have no idea what the above line really does
FragmentManager fm = this.activity.getFragmentManager();
FragmentTransaction t = fm.beginTransaction();
t.replace(R.id.menu_fragment, this.menu);
t.commit();
}
}
为什么不调用模块的provideMenuAdapterGenerator方法来注入我的MenuAdapterGenerator?如果我在该方法中设置了一个断点,它将永远不会跳闸。但是正在创建MenuDaggerModule,因为System.out.println(“ test”); 被击中。
我的理解是,如果创建了MenuDaggerModule(确实如此),则Dagger应该在遇到@Injects MenuAdapterGenerator时使用该provideMenuAdapterGenerator()。我有什么问题?
匕首有很多魔力,但没那么多。您仍然需要告诉Dagger注入实例。
我想假设您MenuFragment
在您的参考资料中有对您的引用MainActivity
。创建时Fragment
,您需要通过调用来告诉Dagger注入它ObjectGraph.inject(T)
:
MenuFragment fragment = new MenuFragment();
this.objectGraph.inject(fragment);
Transaction transaction = getFragmentManager().beginTransaction();
// etc.
Dagger现在将注意到@Inject
您的上的注释MenuAdapterGenerator
,并调用provideMenuAdapterGenerator()
以将其注入。
我想推荐我的另一个答案,其中讨论了构造函数注入。尽管Fragment
s是少数几种情况之一(与Activity
s和View
s一起)是不可能的,但您可能要考虑使用该技术来注入其他可能的自定义类。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句