作为一个码农,什么都不用多讲,贴代码
build project
build module
Application
public class App extends Application { private AppComponent appComponent; @Override public void onCreate() { super.onCreate(); appComponent= DaggerAppComponent.builder() .appModule(new AppModule(this)) .build(); } public AppComponent getAppComponent() { return appComponent; } }
AppComponent
@Singleton @Component(modules = { AppModule.class }) public interface AppComponent { @ContextLife("Application") App getApplication(); RetrofitHelper retrofitHelper(); //提供http的帮助类 }
AppModule
@Module public class AppModule { private App application; public AppModule(App application){ this.application=application; } @Provides @Singleton @ContextLife("Application") public App provideApplication(){ return application; } @Provides @Singleton public RetrofitHelper provideRetrofitHelper() { return new RetrofitHelper(); } }
ActivityComponent
@ActivityScope @Component(dependencies = AppComponent.class, modules = ActivityModule.class)//关联上下 public interface ActivityComponent { Activity getActivity(); void inject(LoginActivity loginActivity);//要在类中使用注入功能 void inject(MainActivity mainActivity); }
ActivityModule
@Module public class ActivityModule { private Activity mActivity; public ActivityModule(Activity activity) { this.mActivity = activity; } @Provides @ActivityScope public Activity provideActivity() { return mActivity; } @Provides @ActivityScope public IPresenterFactory providePresenter(RetrofitHelper retrofitHelper) { return new PresenterFactory(retrofitHelper); } }
Base里面使用注入,否则无法注入
public abstract class PresenterActivity extends BaseActivity { private final static String TAG = "PresenterActivity"; protected abstract void initInject(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); initInject(); } protected ActivityComponent getActivityComponent(){ return DaggerActivityComponent.builder() .appComponent(App.getInstance().getAppComponent()) .activityModule(getActivityModule()) .build(); } private ActivityModule getActivityModule() { return new ActivityModule(this); } }
此时前提条件都有了
点击运行自动生成注入代码(没问题的前提)
使用注入:
public class MainActivity extends PresenterActivity { @Inject protected IPresenterFactory mPresenter;//没有创建对象,inject标签注入类型 private final int BASIC_PERMISSION_REQUEST_CODE = 100; private TextView username; @Override public void findView() { username = findView(R.id.username); username.setText(App.getInstance().getUserEntity().getName()+" hello"); } @Override public void init() { if (mPresenter != null){ Toasts.showShort("mPresenter success",context);//注入成功会打印出success } } @Override public int layoutResID() { return R.layout.activity_main; } @Override protected void initInject() { getActivityComponent().inject(this); } @Subscribe(threadMode = ThreadMode.MAIN) public void onEvent() { Toasts.showShort("刷新UI",context); } }