Android Dagger-为子组件生成器设置动态值
我想在构建子组件生成器时为其设置一个值。如果涉及到简单匕首2,我们可以实现如下目标:Android Dagger-为子组件生成器设置动态值,android,dependency-injection,dagger-2,dagger,Android,Dependency Injection,Dagger 2,Dagger,我想在构建子组件生成器时为其设置一个值。如果涉及到简单匕首2,我们可以实现如下目标: @UserScope @Subcomponent(modules = {UserModule.class, ActivityBuilder.class, NewEditQuotationModule.class}) public interface UserComponent { NewEditQuotationComponent.Builder getNewEditQuotationComponent();
@UserScope
@Subcomponent(modules = {UserModule.class, ActivityBuilder.class, NewEditQuotationModule.class})
public interface UserComponent {
NewEditQuotationComponent.Builder getNewEditQuotationComponent();
void inject(UserManager userManager);
@Subcomponent.Builder
interface Builder {
@BindsInstance
Builder user(User user);
UserComponent build();
}}
但对于Dagger Android,子组件及其关联的构建器由@contributesandroid处理。Dagger自动生成子组件及其生成器,甚至在当前上下文中生成其实现
我想在构建Dagger Android子组件时设置一些值。我尝试了以下方法:
@Subcomponent(modules = NewEditQuotationModule.class)
public interface NewEditQuotationComponent extends AndroidInjector<InquiriesEditNewMainActivity> {
@Subcomponent.Builder
abstract class Builder extends AndroidInjector.Builder<InquiriesEditNewMainActivity> {
@BindsInstance
public abstract Builder setName(@Named("My_Name") String name);
}}
@Module
public abstract class NewEditQuotationModule {
@Binds
@IntoMap
@ActivityKey(InquiriesEditNewMainActivity.class)
abstract AndroidInjector.Factory<? extends Activity>
bindInquiriesEditNewMainActivityInjectorFactory(NewEditQuotationComponent.Builder builder);
}
但是没有成功。
请让我知道
dagger.android
通过在onCreate
中自动创建组件来工作,并且需要以这种方式工作,因为允许android自己创建您的活动。预先创建你的雄激素注射将不起作用;这就是你以前的方法的问题所在
正如我试图通过重复的问题投票指出的那样,您在dagger.android中设置模块实例或@BindsInstance
值的唯一方法是将其作为@Subcomponent.Builder
。这将允许您从活动实例中提取值,并在活动图中设置它们
尽管您始终可以将数据存储在
@Singleton
(ApplicationComponent作用域)对象或VM全局变量中,但您正在尝试做正确的事情,在不设置全局状态的情况下小心地将数据从一个活动传递到另一个活动。我认为这是正确的方法,但您的解决方案可能不会显式地构建雄激素注射子。相反,这是将参数和其他数据转换为活动的惯用方法;然后,您可以将该数据从seedInstance
中活动实例的getIntent().getExtras()
中拉出,从而将其插入到图形中。@JeffBowman:我的场景是,某个日期来自上一个活动,当前活动有5个片段,所有这些片段都需要该数据。因此,我希望在构建时在activitie的组件中设置这些数据,从而提供这些数据。我认为你建议的方法行不通。你能帮我解决这个问题吗?你说得对。谢谢,这很有效。
AndroidInjector.Builder androidInjector = MyApplication
.getApplication()
.getAppComponent()
.getApiEndPoint()
.getApiEndPointComponent()
.getUserManager()
.getUserComponent()
.getNewEditQuotationComponent().setName("My Name");
androidInjector.seedInstance(this);
androidInjector.build();