Android 刀柄-碎片中的入口点
我用剑柄做DI,我有这门课Android 刀柄-碎片中的入口点,android,kotlin,dagger-hilt,Android,Kotlin,Dagger Hilt,我用剑柄做DI,我有这门课 class ChatCore @Inject constructor() 此类需要在片段中注入,而不将片段标记为@AdroidEntryPoint,因为此片段可以附加到未标记为@AndroidEntryPoint的活动 我怎样才能做到这一点。我尝试使用EntryPoint,但最终出错 class MyFragment : Fragment() { lateinit var chatCore: ChatCore @EntryPoint @Instal
class ChatCore @Inject constructor()
此类需要在片段中注入,而不将片段标记为@AdroidEntryPoint
,因为此片段可以附加到未标记为@AndroidEntryPoint
的活动
我怎样才能做到这一点。我尝试使用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
,则需要@在不同的组件中安装模块(包含依赖项)。
例如,在应用程序组件
中,而不是片段组件
然后还需要使用相应的EntryPointAccessors.fromXyz(…)
方法。例如,对于安装在ApplicationComponent
中的模块,您应该使用EntryPointAccessors.fromApplication(…)
是的。我后来意识到了这一点,并在将其放入应用程序组件后进行了修复,我已经更新了我的答案。哦。对不起,我没注意到。你应该发布自己的答案,而不是对你的问题进行编辑。哦,好的。很抱歉给你带来了困惑。谢谢你给出详细的回答!