我可以使用依赖注入成功Realm
,我可以将@Inject
用于活动而没有任何问题,现在我想使用它并将其注入到Fragments中,因为我新手使用这种方法,我不能这样做
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);
}
我如何编辑或创建其他类组件和模块以注入领域?顺便说一下,我的应用程序上有更多片段
提前致谢
答案 0 :(得分:0)
只需在组件中添加另一个目标方法,例如
@Component(modules = ApplicationModule.class)
@Singleton
public interface ApplicationComponent {
void inject(ActivityRegister target);
void inject(ActivityMain target);
void inject(SocketServiceProvider target);
void inject(MyFragment target);
}
在你的片段中,你做了类似的事情。
public class MyFragment extends Fragment{
@inject Realm realm;
@Override
protected void onCreate(Bundle savedInstanceState) {
((MyApplication) getActivity().getApplication()).getComponent().inject(this);
}