所以我的问题是,当我开始使用 Hilt 时,我们是否需要使用 @AndroidEntryPoint 注释标记所有活动,或者我们是否可以创建一个 BaseActivity 并将其扩展到 AppCompactActivity 并将该单个类标记为入口点?
这行得通吗?这种风格的缺点是什么(如果有)?
谢谢。
我一直遇到柄注入问题,因为我对 DI 的概念相对较新,这是问题,我有一个管理我的应用程序会话的类(共享首选项),我想将该类注入到我的用例中(活动/ Fragment),现在当我这样做时,它会抛出此错误
“lateinit property sessionManager尚未初始化”
SessionManager.kt 的代码
class SessionManager @Inject constructor(private val preferences: SharedPreferences) {
fun getTheme() = preferences.getInt(Constants.THEME_KEY, AppCompatDelegate.MODE_NIGHT_NO)
fun setTheme(value: Int) {
val editor = preferences.edit()
editor.putInt(Constants.THEME_KEY, value)
editor.apply()
}
}
Run Code Online (Sandbox Code Playgroud)
appmoudle.kt 的代码
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Singleton
@Provides
fun provideSharedPreferences(@ApplicationContext context: Context) =
context.getSharedPreferences(
Constants.PREF_NAME, Context.MODE_PRIVATE
)
@Singleton
@Provides
fun provideSessionManager(preferences: SharedPreferences) =
SessionManager(preferences)
}
Run Code Online (Sandbox Code Playgroud)
我将其注入的活动的代码
@AndroidEntryPoint
class TrendingRepoActivity : BaseActivity(), View.OnClickListener {
private lateinit var viewModel: TrendingRepoViewModel
private lateinit var binding: ActivityTrendingReposBinding
@Inject …
Run Code Online (Sandbox Code Playgroud)