Dagger 2:如何在Fragment中使用注入

8

我正在使用AndroidInjection.inject(this)将组件注入到活动中。

AndroidInjection还有一个重载的方法,它以android.app.Fragment作为参数。但是我的片段扩展了android.support.v4.app.Fragment,没有相应的方法。

问题:如果一个片段扩展了android.support.v4.app.Fragment,如何使用注入?


2
你尝试过从dagger-android-support中使用AndroidSupportInjection.inject()吗? - Jans
@xhamr 谢谢,这个方法可能有效。但是现在,在我添加了建议的代码并为我的片段声明了DispatchingAndroidInjector之后,一些奇怪的事情开始失败,要求使用@Provides注释的方法...我正在努力弄清楚这个问题。 - Sasha Shpota
1个回答

11

如果您需要支持库片段,则需要使用支持注入。下面是一些示例:

@Singleton
@Component(modules = {
        AndroidSupportInjectionModule.class, // Important
        ActivityModule.class,
        FragmentModule.class
})

public interface AppComponent extends AndroidInjector<App> {

    void inject(App app);

    @Component.Builder
    interface Builder {
        @BindsInstance
        Builder application(Application application);
        AppComponent build();
    }
}

如果你需要例如Multidex实现,那么你可以使用DaggerApplication或简单的HasSomeInjection:

public class App extends MultiDexApplication implements
    HasActivityInjector,
    HasFragmentInjector {

    @Inject DispatchingAndroidInjector<Activity> activityInjector;
    @Inject DispatchingAndroidInjector<Fragment> fragmentInjector;
    private AppComponent mComponent;

    @Override
    public void onCreate() {
        mComponent = DaggerAppComponent.builder().application(this).build();
        mComponent.inject(this);
    }

    // Dependency Injection
    @Override
    public DispatchingAndroidInjector<Activity> activityInjector() {
        return activityInjector;
    }

    @Override
    public DispatchingAndroidInjector<Fragment> fragmentInjector() {
        return fragmentInjector;
    }
}

下一个模块:

@Module
public abstract class FragmentModule {
    @ContributesAndroidInjector
    abstract ContactsFragment bindContactsFragment();
}

活动模块:

@Module
public abstract class ActivityModule {
    @ContributesAndroidInjector
    abstract ContactsActivity bindContactsActivity();
}

还有片段:

import com.some.ContactsPresenter;
import dagger.android.support.DaggerFragment;

public class ContactsFragment extends DaggerFragment {

    @Inject
    ContactsPresenter mContactsPresenter;

    // .....
}

如果您不想使用DaggerFragment,您可以打开它的实现并将其复制到带有必要更改的碎片中。这里的主要功能是使用AndroidSupportInjectionModule。希望这能帮助您。


谢谢。我不得不修复更多的问题,但最终它起作用了。我仍然无法理解为什么在Android中,像DI这样简单的模式会有如此复杂的实现。我希望未来情况会变得更好,但现在我几乎无法强迫自己完成我在Android中计划做的事情。 - Sasha Shpota
从技术上讲,快捷方式是在系统为您创建的对象内使用服务定位器模式。这样,您就不需要创建一个未作用域限定的子组件和一个分派注入器来进行分层查找,以找到可以处理确切类型(dagger-android)的注入器。 - EpicPandaForce

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接