我正在将 Hilt 用于 DI,并且我有这门课。
class ChatCore @Inject constructor()
这个类需要在fragment中注入(inject),不用将fragment标记为@AdroidEntryPoint
因为此 fragment 可以附加到未标记为 @AndroidEntryPoint
的 Activity 上我怎样才能做到这一点。我尝试使用 EntryPoint,但最终出现错误。
class MyFragment : Fragment() {
lateinit var chatCore: ChatCore
@EntryPoint
@InstallIn(FragmentComponent::class)
interface ChatCoreProviderEntryPoint{
fun chatCore():ChatCore
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val hiltEntryPoint = EntryPointAccessors.fromFragment(this, ChatCoreProviderEntryPoint::class.java)
chatCore = hiltEntryPoint.chatCore()
}
通过将其添加到应用程序容器中来解决它。
@EntryPoint
@InstallIn(ApplicationComponent::class)
interface ChatCoreProviderEntryPoint{
fun chatCore():ChatCore
}
val hiltEntryPoint = EntryPointAccessors.fromApplication(applicationContext,
ChatCoreProviderEntryPoint::class.java)
最佳答案
如果您不想使用 AndroidEntryPoint
为您的Fragment
您需要 @Install
你的模块(包含你的依赖)在不同的Component
.
例如。在 ApplicationComponent
内不是 FragmentComponent
.
然后你还需要使用相应的EntryPointAccessors.fromXyz(...)
方法。例如。对于安装在 ApplicationComponent
中的模块你应该使用 EntryPointAccessors.fromApplication(...)
.
关于android - Hilt - fragment 中的入口点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63348908/