如何将片段注入活动,以便我不必手动创建其实例?

问题描述 投票:3回答:1

我正在开发一个Android项目并使用Dagger2进行依赖注入?我试图将Fragment注入Activity,但我不想创建片段实例,使用newInstance或new SomeFragment并希望实例由dagger创建并注入。

我也想知道如果想传递一些参数我怎么能这样做。

android android-fragments dagger-2 dagger
1个回答
1
投票

即使你不想调用new,Android也会:这就是为什么Fragment is required to have a zero-arg public constructor,因为如果你从一个包中恢复FragmentActivity,Android将会reflectively call the Fragment constructor

因此,您创建的大多数片段不应该声明自己的构造函数,当然也不应该有一个带参数的@Inject注释构造函数:只要存在零参数公共构造函数,Android就不会抱怨,但Dagger不会参与以这种方式创建Fragment,如果有两种不相关的方法来创建Fragment,它将降低您阅读和理解代码的能力。

相反,您可以使用newInstance创建一个Fragment实例,其参数在Bundle中设置,然后您可以在Fragment#onCreate中读取和展开。如果你没有传递任何参数,你可以明确地调用new,但newInstance可能是一个很好的一致实践,所以如果Fragment有参数,那么改变就更少了。

要在Fragment实例中获得Dagger提供的依赖项,标准做法是[在AndroidInjection.inject(this)中调用AndroidSupportInjection.inject(this)onAttach,就像在dagger.android docs on injecting Fragment中一样。这样做的简单方法是inheriting from DaggerFragment,但您也可以自己这样做。要查找注入Fragment的组件,AndroidSupportInjection将递归检查扩展HasSupportFragmentInjector的Fragment的父层次结构,然后尝试Activity,然后是Application;如果你使用带有ContributesAndroidInjector的dagger.android的标准设计,Dagger将为你的Fragment创建一个子组件实例,允许你引入Fragment-scoped依赖项。

© www.soinside.com 2019 - 2024. All rights reserved.