[英]Dagger2 nullable injection
我正在嘗試用 Dagger 注入 Glide。
所以我有AppModule:
@Module
class AppModule {
@Provides
fun provideRequestOptions(): RequestOptions {
return RequestOptions()
.placeholder(R.drawable.white_background)
.error(R.drawable.white_background)
}
@Provides
fun provideGlideInstance(application: Application, requestOptions: RequestOptions): RequestManager{
return Glide.with(application).setDefaultRequestOptions(requestOptions)
}
@Nullable
@Provides
fun provideAppDrawable(application: Application): Drawable? {
return ContextCompat.getDrawable(application, R.drawable.logo)
}
}
和 AuthActivity:
class AuthActivity : DaggerAppCompatActivity() {
lateinit var binding: ActivityAuthBinding
@Inject
lateinit var logo: Drawable
@Inject
lateinit var requestManager: RequestManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityAuthBinding.inflate(layoutInflater)
setContentView(binding.root)
setLogo()
}
private fun setLogo() {
requestManager.load(logo).into(binding.loginLogo)
}
}
AppModule 中的provideAppDrawable()
必須返回可為空的Drawable?
. 當我嘗試構建應用程序時,Dagger 抱怨它的可空性:
\AppComponent.java:7: error: [Dagger/Nullable] android.graphics.drawable.Drawable is not nullable, but is being provided by @org.jetbrains.annotations.Nullable @androidx.annotation.Nullable @Provides android.graphics.drawable.Drawable com.example.daggercodingwithmitch.di.AppModule.provideAppDrawable(android.app.Application)
public abstract interface AppComponent extends dagger.android.AndroidInjector<com.example.daggercodingwithmitch.BaseApplication> {
首先,我嘗試使AuthActivity
中的logo
var 可以為空,但 lateinit 不能為空。 如果我不使用 lateinit 並像這樣制作: var logo: Drawable? = null
var logo: Drawable? = null
我收到關於私有字段注入的奇怪錯誤,即使它不是私有的:
\AuthActivity.java:10: error: Dagger does not support injection into private fields
private android.graphics.drawable.Drawable logo;
我該如何解決? 謝謝。
最簡單的方法是讓 provideAppDrawable 返回 Drawable 而不是 Drawable? 並從中刪除 @Nullable 。 是否有任何情況下返回 null 這不是錯誤? 如果不是,它不應該是一個可為空的變量。
您還需要標記歸檔的“徽標”@Nullable。
如果@Provides 方法被標記為@Nullable,Dagger 將只允許注入也標記為@Nullable 的站點。 嘗試將@Nullable 配置與非@Nullable 注入站點配對的組件將無法編譯。
將 logo 字段設為可為空。 Dagger 不允許將可為空的 object 注入到不可為空的字段中。
@Inject
var logo: Drawable?=null
在 Java 中,
@Nullable
@Inject
Drawable logo;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.