Dagger2片段注射

时间:2018-02-07 16:21:26

标签: android dagger-2 dagger

尝试学习Dagger2并使用Dagger2 2.14.1。我无法过去:

no suitable method found for inject(SettingsFragment)

SettingsFragment是:

public class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {
....
 @Override
public void onAttach(Context context){
    AndroidInjection.inject(this);     <<<< Error here
    super.onAttach(context);
}}

因为我无法从DaggerFragment扩展PreferenceFragmentCompat。

我的构建器模块是

@Module(subcomponents = {SettingsFragmentSubComponent.class, StartupPhotoFragmentSubComponent.class })
public abstract class UIBuildersModule {

@Binds
@IntoMap
@FragmentKey(SettingsFragment.class)
abstract AndroidInjector.Factory<? extends Fragment> bindSettingsFragmentInjectorFactory(SettingsFragmentSubComponent.Builder builder);

//    @ContributesAndroidInjector    <<< tried also without luck.
//    abstract SettingsFragment bindSettingsFragment();

@ContributesAndroidInjector
abstract StartupPhotoFragment bindStartupPhotoFragment();

我确实为SettingsFragment创建了模块和子组件,这些组件和子组件实际上是空的,因为我想获得我在应用程序级别创建的依赖项:

@Module
public class SettingsFragmentModule {
}

@Subcomponent(modules = {SettingsFragmentModule.class})
public interface SettingsFragmentSubComponent extends 
AndroidInjector<SettingsFragment> {

@Subcomponent.Builder
abstract class Builder extends AndroidInjector.Builder<SettingsFragment> {
}}

编辑:添加了包含UIBuildersModule的ApplicationComponent和build.gradle中的代码段

@Singleton
@Component(modules = {UIBuildersModule.class, 
AndroidSupportInjectionModule.class, ApplicationModule.class, })
public interface ApplicationComponent extends
    AndroidInjector<ActivityTrackerApplication> {

@Component.Builder
interface Builder {
    @BindsInstance
    Builder application(ActivityTrackerApplication application);
    ApplicationComponent build();
}
void inject(ActivityTrackerApplication activityTrackerApplication);
void inject(StartupPhotoFragment startupPhotoFragment);
void inject(SettingsFragment settingsFragment);

}

此处还有build.gradle的片段

final DAGGER_VERSION="2.14.1"
 ....
// For Dagger2
compile "com.google.dagger:dagger:$DAGGER_VERSION"
compile "com.google.dagger:dagger-android:$DAGGER_VERSION"
compile "com.google.dagger:dagger-android-support:$DAGGER_VERSION"
annotationProcessor "com.google.dagger:dagger-android-processor:$DAGGER_VERSION"
annotationProcessor "com.google.dagger:dagger-compiler:$DAGGER_VERSION"

EDIT2:解决方案 啊 - 但当然。

public class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {
....
 @Override
public void onAttach(Context context){
    AndroidSupportInjection.inject(this); <<<<Needed AndroidSupportInjection
    super.onAttach(context);
}}

0 个答案:

没有答案