android - Hilt - fragment 中的入口点

标签 android kotlin dagger-hilt

我正在将 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/

相关文章:

android - 强制关闭不会退出 android 应用程序,而是打开一个处于错误状态的先前 Activity

android - 我如何在我的项目中使用谷歌代码中的源代码?

android - Koin 依赖项覆盖在测试中不起作用

android - 以编程方式获取指南百分比大小(以像素为单位)

Android Dagger Hilt : Do we need scope annotations for ViewModels?

android - Hilt 集成使应用程序 MainActivity_GeneratedInjector 崩溃

安卓 : How to get the src of an imageButton

android - Spanned CSS 样式/颜色

android - 使用 Hilt 提供首选项数据存储

android - 在 Activity 之间共享 DBAdapter