经过上一篇android studio 配置dragger我们已经在android studio 配置好dagger ;接下来我们要写第一个依赖注入啦:)
为了能够快速上手,写出第一个demo来,接下来直接就进入写代码流程环节:
第一步:写
Module
AppModule
@Module(includes = {ToastModule.class})public class AppModule {private App app;public AppModule(App app) {this.app = app;}@Provides@Singletonpublic Application provideApplicationContext() {return app;}}
ToastModule
@Module(injects = {App.class,MainActivity.class},complete = false, library = true)public class ToastModule {@Provides@Singletonpublic Toast provideToast(Application application) {return Toast.makeText(application, \"\", Toast.LENGTH_SHORT);}}
第二步:构建依赖注入图并注入
public class App extends Application {private ObjectGraph applicationGraph;@InjectToast toast;@Overridepublic void onCreate() {super.onCreate();applicationGraph = ObjectGraph.create(getModules().toArray());applicationGraph.inject(this);toast.setText(\"hello dagger\");toast.show();}protected List<Object> getModules() {return Arrays.<Object>asList(new AppModule(this));}}
至此hello dagger demo 已经完成。
转载于:Android开发/578888