gpt4 book ai didi

java - Dagger2子组件如何注入(inject)到Fragment中?

转载 作者:行者123 更新时间:2023-12-02 02:39:09 27 4
gpt4 key购买 nike

如何在 Fragment 中注入(inject) dagger2 子组件。我在 Activity 中使用相同的子组件,效果很好。我如何初始化 fragment 中的模块。

我的 fragment 的一部分

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);

DgFirebaseSubComponent.Builder builder = (DgFirebaseSubComponent.Builder)
((AttendanceApplication) getActivity().getApplication()).getApplicationComponent()
.subcomponentBuilders()
.get(DgFirebaseSubComponent.Builder.class)
.get();
builder.activityModule(new DgFirebaseSubModule(??how can i initialize module ??)).build().inject(this);

}

我的 DgFirebaseSubComponent.java

@DgFirebaseScope
@Subcomponent(modules={ DgFirebaseSubModule.class })
public interface DgFirebaseSubComponent {

void inject(DgAllEmpsAbsMvvmActivity activity);
void inject(DgAllEmpsAbsListFragment fragment);

SharedPreferences sharedPreferences();

@Subcomponent.Builder
interface Builder extends SubcomponentBuilder<DgFirebaseSubComponent> {
Builder activityModule(DgFirebaseSubModule module);
}

}

我的 DgFirebaseSubModule.java

@Module
public class DgFirebaseSubModule {
private final DgAllEmpsAbsMvvmActivity activity;

public DgFirebaseSubModule(DgAllEmpsAbsMvvmActivity activity) { this.activity = activity; }


@Provides
@FirebaseScope
SharedPreferences providesSharedPreferences(Application application) {
return PreferenceManager.getDefaultSharedPreferences(application);
}


}

最佳答案

模块不必用 Activity 实例化。我已经更改了 DgFirebaseSubModule.java

@Module
public class DgFirebaseSubModule {

public DgFirebaseSubModule() { }


@Provides
@FirebaseScope
SharedPreferences providesSharedPreferences(Application application) {
return PreferenceManager.getDefaultSharedPreferences(application);
}

}

并注入(inject) fragment

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);

DgFirebaseSubComponent.Builder builder = (DgFirebaseSubComponent.Builder)
((AttendanceApplication) getActivity().getApplication()).getApplicationComponent()
.subcomponentBuilders()
.get(DgFirebaseSubComponent.Builder.class)
.get();
builder.activityModule(new DgFirebaseSubModule()).build().inject(this);

}

关于java - Dagger2子组件如何注入(inject)到Fragment中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45771830/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com