如何在mainModule类中提供活动上下文?谢谢!代码如下所示:
@Singleton @Component(modules = {AndroidInjectionModule.class,AppModule.class,ActivityBuilder.class}) public interface AppComponent { @Component.Builder interface Builder { @BindsInstance Builder application(Application application); AppComponent build(); } void inject(MvmApp app); }
Activtity builder:
@Module public abstract class ActivityBuilder { @ContributesAndroidInjector(modules = {MainModule.class}) abstract MainActivity bindMainActivity(); }
我有一个appModule,每个活动都有一个模块:
@Module public class AppModule { @Provides @Singleton @ApplicationContext Context provideContext(Application application) { return application; } @Provides @Singleton DataManager provideDataManager(AppDataManager appDataManager) { return appDataManager; } @Provides @DatabaseInfo String provideDatabaseName() { return "carDatabase"; } @Provides @Singleton AppDataBase provideAppDatabase(@DatabaseInfo String dbName,@ApplicationContext Context context) { return Room.databaseBuilder(context,AppDataBase.class,dbName) .build(); } @Provides @Singleton DbHelper provideDbHelper(AppDbHelper appDbHelper) { return appDbHelper; } }
AppClass:
public class MvmApp extends Application implements HasActivityInjector { @Inject DispatchingAndroidInjector<Activity> activityDispatchingAndroidInjector; @Override public void onCreate() { super.onCreate(); DaggerAppComponent.builder() .application(this) .build() .inject(this); } @Override public DispatchingAndroidInjector<Activity> activityInjector() { return activityDispatchingAndroidInjector; } }
我的所有活动都扩展了基础活动,注入了Dagger家属.
public abstract class BaseActivity extends AppCompatActivity implements MvpView { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidInjection.inject(this); } }
在mainModule中,我需要提供活动的上下文.
@Module public class MainModule { @Provides MainMvpPresenter<MainMvpView> provideMainPresenter( MainPresenter<MainMvpView> presenter) { return presenter; } @Provides CompositeDisposable provideCompositeDisposable() { return new CompositeDisposable(); } @Provides CarAdapter provideCarAdapter( @ActivityContext Context context) { return new CarAdapter(context); } }
解决方法
解决方案是:
@Module public class MainModule { @Provides MainMvpPresenter<MainMvpView> provideMainPresenter( MainPresenter<MainMvpView> presenter) { return presenter; } @Provides CompositeDisposable provideCompositeDisposable() { return new CompositeDisposable(); } @Provides CarAdapter provideCarAdapter(MainActivity activity) { return new CarAdapter(activity); } }