Android Studio 3.4
dagger-android 2.21
如何使用新的activity
将dagger-android
传递给匕首模块
在使用旧版本的dagger之前,我们可以在构造函数中传递Activity并在provider方法中返回它。但我不知道如何用dagger-android做到这一点
我有以下模块。然而,匕首现在不关于ForecastActivity
。
@Module
class ActivityModule {
@Reusable
@Provides
fun provideRetryListener(forecastActivity: ForecastActivity): RetryListener {
return forecastActivity
}
}
RetryListener
是ForecastActivity
实现的接口。我希望能够将这个RetryListener
注入我的RetryFragment
,即
class RetryFragment : Fragment() {
@Inject
lateinit var retryListener: RetryListener // Inject here
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
AndroidSupportInjection.inject(this)
super.onCreateView(inflater, container, savedInstanceState)
retryListener.onRetry() // usage like this
return inflater.inflate(R.layout.failurecase_layout, container, false)
}
}
在forecastActivity中
class ForecastActivity : AppCompatActivity(), RetryListener {
@Inject
lateinit var forecastPresenter: ForecastPresenter
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
}
override fun onRetry() {
/* do something here */
}
}
我的ActivityBuilder如下:
@Module
abstract class ActivityBuilder {
@ContributesAndroidInjector(modules = [ActivityModule::class])
abstract fun injectIntoRetryFragment(): RetryFragment
}
我的组件是这样的:
@Singleton
@Component(modules = [
AndroidSupportInjectionModule::class,
ActivityBuilder::class,
ActivityModule::class])
interface StockComponent {
@Component.Builder
interface Builder {
@BindsInstance
fun application(application: StockApplication): Builder
fun build(): StockComponent
}
fun inject(application: StockApplication)
}
我的申请是:
class StockApplication : Application(), HasActivityInjector, HasSupportFragmentInjector {
@Inject
lateinit var dispatchingAndroidActivityInjector: DispatchingAndroidInjector<Activity>
@Inject
lateinit var dispatchingAndroidFragmentInjector: DispatchingAndroidInjector<Fragment>
override fun onCreate() {
super.onCreate()
DaggerStockComponent
.builder()
.application(this)
.build()
.inject(this)
}
override fun activityInjector(): AndroidInjector<Activity> {
return dispatchingAndroidActivityInjector
}
override fun supportFragmentInjector(): AndroidInjector<Fragment> {
return dispatchingAndroidFragmentInjector
}
}
所以问题是当使用dagger-android时如何将RetryListener
注入RetryFragment
,RetryListener
是由ForecastActivity
实现的?
提前谢谢了
我看不到提供你的ForecastActivity
的模块,即:
@ContributesAndroidInjector
abstract fun forecastActivity(): ForecastActivity
Activity
将需要实施HasSupportFragmentInjector
,并提供DispatchingAndroidInjector<Fragment>