如果没有 @Provides 注释方法,则无法提供字符串

String cannot be provided without an @Provides-annotated method

我正在尝试在一个简单的项目中使用 ActivityScopedActivityComponent,但出现以下错误

@javax.inject.Named("String2") java.lang.String cannot be provided without an 
@Provides-annotated method.
public abstract static class SingletonC implements BaseApplication_GeneratedInjector,
@javax.inject.Named("String2") java.lang.String is injected at
      com.example.hiltoplayground.TestViewModel(testString)
  com.example.hiltoplayground.TestViewModel is injected at
      com.example.hiltoplayground.TestViewModel_HiltModules.BindsModule.binds(vm)
  @dagger.hilt.android.internal.lifecycle.HiltViewModelMap 
 java.util.Map<java.lang.String,javax.inject.Provider<androidx.lifecycle.ViewModel>> 
 is requested at
      dagger.hilt.android.internal.lifecycle.HiltViewModelFactory.ViewModelFactoriesEntryPoint.getHiltViewModelMap() [com.example.hiltoplayground.BaseApplication_HiltComponents.SingletonC → com.example.hiltoplayground.BaseApplication_HiltComponents.ActivityRetainedC → com.example.hiltoplayground.BaseApplication_HiltComponents.ViewModelC]

但是如果我使用 SingletonComponent@Singleton 它运行完美,没问题。

这是受影响的模块

@Module
@InstallIn(ActivityComponent::class)
object MainModule {

    @ActivityScoped
    @Provides
    @Named("String2")
    fun provideTestString2 (
        @ApplicationContext context: Context
    ) = context.getString(R.string.string_inject)
}

下面是 ViewModel(我猜这里没问题)

@HiltViewModel
class TestViewModel @Inject constructor(
    @Named("String2") testString: String): ViewModel() {

        init{
            Log.d("String2Message","Show $testString")
        }
}

您可以使用 @ActivityRetainedScoped 代替 @ActivityScoped 并从 @InstallIn(ActivityComponent::class) 生成 @InstallIn(ActivityRetainedComponent::class)