Android Hilt - 多模块项目转换错误

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

我正在尝试将 hilt 用于包含动态功能的项目。我面临一个错误,我无法完全理解原因。我收到这样的错误:

java.lang.ClassCastException: com.social.analysis.DaggerApp_HiltComponents_ApplicationC$ActivityRetainedCImpl$ActivityCImpl$FragmentCImpl cannot be cast to com.social.login.intro.IntroFragment_GeneratedInjector
    at com.social.login.intro.Hilt_IntroFragment.inject(Hilt_IntroFragment.java:94)
    at com.social.login.intro.Hilt_IntroFragment.initializeComponentContext(Hilt_IntroFragment.java:58)
    at com.social.login.intro.Hilt_IntroFragment.onAttach(Hilt_IntroFragment.java:50)
    at androidx.fragment.app.Fragment.onAttach(Fragment.java:1602)
    at com.social.login.intro.Hilt_IntroFragment.onAttach(Hilt_IntroFragment.java:40)

登录模块中的我的 ViewModel(动态功能)

class IntroViewModel @Inject constructor(): ViewModel() {
// TODO: Implement the ViewModel
}

登录模块中的我的片段

@AndroidEntryPoint
class IntroFragment : BaseFragment<FragmentIntroBinding, IntroViewModel>(
R.layout.fragment_intro
) {

companion object {
    fun newInstance() = IntroFragment()
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
}

override fun onInitDataBinding() {
    viewBinding.viewModel = viewModel
}
}

UI 模块中的我的基础片段

abstract  class BaseFragment <B: ViewDataBinding, M: ViewModel>(
@LayoutRes
private val layoutId: Int
): Fragment() {

@Inject
lateinit var viewModel: M
lateinit var viewBinding: B
...

应用程序模块中的我的应用程序类

@HiltAndroidApp
class App : SplitCompatApplication() {
}

我在应用程序模块中的主要活动

@AndroidEntryPoint
class MainActivity : AppCompatActivity() 

我从 App 模块调用 IntroFragment。然后应用程序崩溃了。

项目结构如下所示:

android android-studio kotlin dagger dagger-hilt
3个回答
12
投票

来自类似问题的回答

删除.gradle目录(在项目基目录中) 使缓存无效并重新启动 Android Studio。


2
投票

如果您使用动态功能模块,请不要忘记删除@AndroidEntryPoint注释。因为注释来自 Hilt,并且您使用 Dagger2 作为 DI。


0
投票

对我来说,问题是我从不同的范围创建了

EntryPointAccessors
。确保您的模块和入口点范围与
EntryPointAccessors
创建类似。

如果您的模块范围是

Singleton

,请使用此选项
@EntryPoint
@InstallIn(SingletonComponent::class)
interface ChatModuleDependencies {

    fun timeHelper(): TimeHelper

}

EntryPointAccessors.fromApplication(
    applicationContext,
    ChatModuleDependencies::class.java
)

如果您的模块范围是

Activity

,请使用此选项
@EntryPoint
@InstallIn(ActivityComponent::class)
interface ChatModuleDependencies {

    fun timeHelper(): TimeHelper

}

EntryPointAccessors.fromActivity(
    this,
    ChatModuleDependencies::class.java
)

等等...

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