击中-片段中的EntryPoint

时间:2020-08-10 22:32:28

标签: android kotlin dagger-hilt

我正在使用Hilt进行DI,我有这个课程。

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)

1 个答案:

答案 0 :(得分:0)

如果您不想为AndroidEntryPoint使用Fragment,则需要@Install在另一个Component中的模块(包含依赖项)。 例如。在ApplicationComponent而非FragmentComponent中。

然后,您还需要使用相应的EntryPointAccessors.fromXyz(...)方法。例如。对于安装在ApplicationComponent中的模块,您应该使用EntryPointAccessors.fromApplication(...)