gpt4 book ai didi

android - Dagger 2、Cicerone、Kotlin - 注入(inject)问题

转载 作者:行者123 更新时间:2023-11-29 02:20:13 28 4
gpt4 key购买 nike

此代码在 Java 中完美运行,但在 Kotlin 中存在未定义的问题

问题:

error: [Dagger/MissingBinding] ru.terrakok.cicerone.Router cannot be provided without an @Inject constructor or an @Provides-annotated method. public abstract void inject(@org.jetbrains.annotations.NotNull()

ru.terrakok.cicerone.Router is injected at com.setname.dagger2ciceronelearning.presentation.main.MainActivity.mRouter

com.setname.dagger2ciceronelearning.presentation.main.MainActivity is injected at com.setname.dagger2ciceronelearning.di.AppComponent.inject(com.setname.dagger2ciceronelearning.presentation.main.MainActivity)

应用组件

@Singleton
@Component(modules = arrayOf(NavigationModule::class))
interface AppComponent {

fun inject(mainActivity: MainActivity)
fun inject(fragmentOne: FragmentOne)
fun inject(fragmentTwo: FragmentTwo)

}

导航模块

@Module
class NavigationModule {

private val firstLevelNavigation: Cicerone<Router> = Cicerone.create()
private val secondLevelNavigation: Cicerone<Router> = Cicerone.create()

@Provides
@Singleton
@Named(Navigation.ROUTER_FIRST_LEVEL)
fun provideFirstLevelRouter(): Router = firstLevelNavigation.router

@Provides
@Singleton
@Named(Navigation.ROUTER_SECOND_LEVEL)
fun provideSecondLevelRouter(): Router = secondLevelNavigation.router

@Provides
@Singleton
@Named(Navigation.NAV_HOLDER_FIRST_LEVEL)
fun provideFirstLevelNavigatorHolder(): NavigatorHolder = firstLevelNavigation.navigatorHolder


@Provides
@Singleton
@Named(Navigation.NAV_HOLDER_SECOND_LEVEL)
fun provideSecondLevelNavigationHolder(): NavigatorHolder = secondLevelNavigation.navigatorHolder

}

学习应用

class LearningApp : Application() {

companion object {

lateinit var appComponent: AppComponent

}

override fun onCreate() {
super.onCreate()
appComponent = DaggerAppComponent
.builder()
.build()
}

}

主 Activity

class MainActivity : AppCompatActivity() {

@Inject
@Named(Navigation.ROUTER_FIRST_LEVEL)
lateinit var mRouter: Router

@Inject
@Named(Navigation.NAV_HOLDER_FIRST_LEVEL)
lateinit var mNavigatorHolder: NavigatorHolder

private lateinit var mNavigator:Navigator

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

LearningApp.appComponent.inject(this)

mNavigator = SupportAppNavigator(this, R.id.main_container)

mRouter.newRootScreen(Screens.FragmentOneScreen())

}

override fun onResume() {
super.onResume()
mNavigatorHolder.setNavigator(mNavigator)
}

override fun onPause() {
mNavigatorHolder.removeNavigator()
super.onPause()
}

}

最佳答案

正如一位非常聪明的人曾经说过的:您需要使用@field:Named 将注释定位到字段。

关于android - Dagger 2、Cicerone、Kotlin - 注入(inject)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56567317/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com