Android在片段上使用依赖注入 [英] Android using Dependency Injection on Fragments

查看:107
本文介绍了Android在片段上使用依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以将Dependency Injection用于 Realm 成功,我可以将 @Inject 应用于活动而没有任何问题,现在我想使用它并将其注入到Fragments中,因为我是新手,因此无法使用

I can use Dependency Injection for Realm successful, i can use @Inject into activity without any problem, now i want to use that and inject that into Fragments, since i novice to use this method, i can't do that

ApplicationModule 类:

@Module
public class ApplicationModule {

    @Provides
    Context provideApplicationContext() {
        return AlachiqApplication.getInstance();
    }

    @Provides
    @Singleton
    RealmConfiguration provideRealmConfiguration() {
        final RealmConfiguration.Builder builder = new RealmConfiguration.Builder()
                .schemaVersion(Migration.SCHEMA_VERSION)
                .deleteRealmIfMigrationNeeded()
                .migration(new Migration());
        return builder.build();
    }

    @Provides
    Realm provideDefaultRealm(RealmConfiguration config) {
        return Realm.getInstance(config);
    }
}

ApplicationComponent 类:

@Component(modules = ApplicationModule.class)
@Singleton
public interface ApplicationComponent {
    void inject(ActivityRegister target);
    void inject(ActivityMain target);
    void inject(FragmentEbooks target);
    void inject(FragmentDocuments target);
    void inject(SocketServiceProvider target);
}

我如何编辑或创建其他类组件和模块以将领域注入其中?顺便说一下,我的应用程序上有更多片段

how can i edit or create other class component and module to inject realm into that? by the way, i have more fragment on my application

预先感谢

推荐答案

只需在您的组件中添加另一个目标方法,例如,

Just add another target method in your component like,

@Component(modules = ApplicationModule.class)
@Singleton
public interface ApplicationComponent {
  void inject(ActivityRegister target);
  void inject(ActivityMain target);
  void inject(SocketServiceProvider target);
  void inject(MyFragment target);
}

在您的片段中做类似的事情。 p>

And in your fragment do similar thing what your doing in your activity.

public class MyFragment extends Fragment{
   @inject Realm realm;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
    ((MyApplication) getActivity().getApplication()).getComponent().inject(this);
}

这篇关于Android在片段上使用依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆