【问题标题】:Dagger 2: How to use injection with a FragmentDagger 2:如何使用 Fragment 进行注入
【发布时间】:2018-09-17 21:46:29
【问题描述】:

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

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

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

【问题讨论】:

  • 你试过AndroidSupportInjection.inject()dagger-android-support吗?
  • @xhamr 谢谢,它可能会工作。但是现在,在我添加了建议的代码并为我的片段声明了DispatchingAndroidInjector 之后,一些有线的东西开始失败,要求使用@Provides-annotated 方法......我正在努力解决这个问题。

标签: java android android-fragments dagger-2 dagger


【解决方案1】:

对于支持库片段,您需要使用支持注入。这里有一些例子:

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

应用程序,如果需要,可以使用 DaggerApplication 或简单的 HasSomeIjection,例如 Multidex implementation:

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。希望对你有帮助

【讨论】:

  • 谢谢。我不得不解决更多问题,但最终它奏效了。我仍然不明白为什么像 DI 这样简单的模式在 Android 中有如此复杂的实现。我希望将来事情会变得更好,但现在我很难强迫自己完成我计划在 Android 中做的事情。
  • 从技术上讲,快捷方式是在系统为您创建的对象中使用服务定位器模式。这样你就不需要创建一个无作用域的子组件和一个用于分层查找的调度注入器来找到可以处理确切类型的注入器(dagger-android)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多