Dagger2子组件如何在Fragment中注入?

时间:2017-08-19 12:59:29

标签: java android android-fragments dagger-2

如何在Fragment中注入dagger2子组件。我在Activity中使用相同的子组件,它运行良好。我如何在片段中初始化模块。

我片段的一部分

@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);
    }


}

1 个答案:

答案 0 :(得分:1)

模块不必使用活动进行实例化。我更改了DgFirebaseSubModule.java

@Module
public class DgFirebaseSubModule {

public DgFirebaseSubModule() {  }


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

}

并注入片段

@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);

}