How can I inject fragment into activity so that I don't have to manually create its instance?

▼魔方 西西 提交于 2020-12-09 16:45:50

问题


I am working on a android project and using Dagger2 for Dependency Injection? I am trying to inject Fragment into Activity but I don't want to create fragment instance , using newInstance or new SomeFragment and want the instance to be created by dagger and injected.

I also want to know how can I do the same if want to some pass some arguments.


回答1:


Even though you don't want to call new, Android will: This is why Fragment is required to have a zero-arg public constructor, because if you restore a FragmentActivity from a bundle, Android will reflectively call the Fragment constructor.

Consequently, most Fragments you create should not declare their own constructors, and certainly shouldn't have an @Inject-annotated constructor that takes parameters: Android won't complain as long as there is a zero-arg public constructor, but Dagger will not participate in creating your Fragment that way, and it will reduce your ability to read and understand your code if there are two unrelated ways to create your Fragment.

Instead, you can use newInstance to create a Fragment instance with arguments set in a Bundle, which you can then read and expand in Fragment#onCreate. If you don't have any arguments to pass, you could call new explicitly, but newInstance might be a good consistent practice so there's less to change if the Fragment ever takes arguments.

To get Dagger-provided dependencies in your Fragment instance, the standard practice is to [call AndroidInjection.inject(this) or AndroidSupportInjection.inject(this) in onAttach, as in the dagger.android docs on injecting Fragment. The easy way to do this is by inheriting from DaggerFragment, but you're also welcome to do so yourself. To find a component to inject your Fragment, AndroidSupportInjection will recursively check up the parent hierarchy for a Fragment that extends HasSupportFragmentInjector, then will try the Activity, and then the Application; if you use the standard design for dagger.android with ContributesAndroidInjector, Dagger will create a subcomponent instance for your Fragment that allows you to introduce Fragment-scoped dependencies.



来源:https://stackoverflow.com/questions/55493834/how-can-i-inject-fragment-into-activity-so-that-i-dont-have-to-manually-create

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!