我有一个自定义 WebView,我添加到我的布局 xml:
<my.company.ui.ExtendedWebView />
它扩展了原生的 WebView:
class ExtendedWebView @JvmOverloads constructor(context: Context,
attrs: AttributeSet? = null, defStyle: Int = 0)
: WebView(context, attrs, defStyle) {
// ...
}
如何使用 Hilt 将 @Singelton
类注入(inject)到上面的类中?属性注入(inject)?我应该如何注释类?
最佳答案
我发现 @AndroidEntryPoint
注释需要在 View、Fragment(如果在 Fragment 中)和 Activity 上。因为注解。
因此,假设您的 DI 设置如下:
/* CONTENTS OF com.org.app.di/dependencyModule.kt */
@Module
@InstallIn(ViewComponent::class)
object DependencyModule {
@Provides
fun provideDependency(@ApplicationContext context: Context): DependencyType
= DependencyInstance(context)
}
我的应用程序设置正确:
@HiltAndroidApp
class SuperAwesomeApplication : Application()
/* Remember to reference this is the manifest file, under the name attricbute! */
现在,如果我有一个带有注入(inject)依赖项的 View :
@AndroidEntryPoint
class SuperAwesomeView(context: Context, attrs: AttributeSet) : View(context, attrs) {
@Inject
lateinit var dependency: DependencyType
...
我会得到错误:
...
Caused by: java.lang.IllegalStateException: class com.app.org.ui.view.SuperAwesomeView, Hilt view must be attached to an @AndroidEntryPoint Fragment or Activity.
...
所以我在包含 View 的 Fragment 中添加了 @AndroidEntryPoint
注释:
@AndroidEntryPoint
class SuperAwesomeFragment : Fragment() {
...
然后我们遇到下一个错误:
Caused by: java.lang.IllegalStateException: Hilt Fragments must be attached to an @AndroidEntryPoint Activity. Found: class com.org.ui.SuperAwesomeActivity
所以我了解到注释需要一直冒泡,从 View 到(如果在 Fragment 中)Fragment,再到 Activity:
@AndroidEntryPoint
class SuperAwesomeActivity : AppCompatActivity() {
...
关于android - 使用 Hilt 注入(inject)类以查看组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64108483/