我有一个主要用Java编写的项目,但我正在放慢向Kotlin的新活动。该项目适用于Dagger2,与基于Java的活动一起使用时效果很好。但是,当我创建Kotlin活动并尝试注入时,我收到以下错误。
如果没有LoginIDPresenter
构造函数或@Inject
- 或@Provides
- 带注释的方法,则无法提供{p> @Produces
。此类型支持成员注入,但不能隐式提供。
void inject(LoginIDActivity loginIDActivity);
com.maxis.mymaxis.ui.logindigitalid.LoginIDPresenter is injected at
com.maxis.mymaxis.ui.logindigitalid.LoginIDActivity.loginIDPresenter
com.maxis.mymaxis.ui.logindigitalid.LoginIDActivity is injected at
com.maxis.mymaxis.injection.component.ActivityComponent.inject(loginIDActivity)
再次重申,当我在Java活动中注入时,它可以完美地运行。此外,我的模块和组件文件都是Java。只有当我创建Kotlin活动并尝试注入时,我才会收到错误。
LoginIDPresenter.kt
class LoginIDPresenter : BasePresenter<LoginIDMvpView>() {
lateinit var mContext : Context
@Inject
fun LoginIDPresenter(@ActivityContext context: Context){
mContext = context
}
override fun attachView(loginIDMvpView: LoginIDMvpView) {
super.attachView(loginIDMvpView)
}
override fun detachView() {
super.detachView()
mCompositeSubscription.clear()
}
}
LoginIDActivity.kt
class LoginIDActivity : BaseActivity(), LoginIDMvpView {
@Inject lateinit var loginIDPresenter : LoginIDPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
loginIDPresenter.attachView(this)
}
override fun showErrorMessageDialog(errorObject: ErrorObject?) {
if (errorObject != null) {
Util.alertDialogBackToLandingPage(this, errorObject.getErrorUiMessage(), R.drawable.error_name)
}
}
override fun getLayoutResourceId(): Int {
return R.layout.activity_login_id
}
override fun injectActivity(component: ActivityComponent?) {
component?.inject(this)
}
override fun setToolBar() {
//no toolbar
}
}
ActivityComponent .java
@PerActivity
@Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class)
public interface ActivityComponent {
.
.
.
void inject(LoginIDActivity loginIDActivity);
.
.
.
}
ActivityModule.java
@Module
public class ActivityModule {
private Context mContext;
public ActivityModule(Context context) {
mContext = context;
}
@Provides
@ForActivity
Activity provideActivity() {
return (Activity) mContext;
}
@Provides
@ActivityContext
Context providesContext() {
return mContext;
}
}
答案 0 :(得分:3)
您的意图是使用@Inject constructor
,但您没有实施它。只需为LoginIDPresenter
提供主要构造函数:
class LoginIDPresenter @Inject constructor(
@ActivityContext val context: Context
) : BasePresenter<LoginIDMvpView>() {
override fun attachView(loginIDMvpView: LoginIDMvpView) {
super.attachView(loginIDMvpView)
}
override fun detachView() {
super.detachView()
mCompositeSubscription.clear()
}
}