我尝试使用DatePickerDialog
提供片段,但是当我使用BasicInfoFragment
作为参数时,会导致错误:Found a dependency cycle
为什么会这样??
@Module
class ActivityModule(val activity: AppCompatActivity) {
@Provides
fun provideActivity() = activity
@Provides
@ActivityContext
fun provideContext(): Context = activity
// [...]
@Provides
fun provideDatePickerDialog(basicInfoFragment: BasicInfoFragment):
DatePickerDialog {
return DatePickerDialog(activity, basicInfoFragment, 1999, 9, 9)
}
}
片段代码:
class BasicInfoFragment @Inject constructor()
: BaseFragment(), BasicInfoMvpView ,
LabelledSpinner.OnItemChosenListener,
DatePickerDialog.OnDateSetListener {
@Inject
lateinit var datePickerDialog: DatePickerDialog
@Inject
lateinit var mPresenter: BasicInfoMvpPresenter<BasicInfoMvpView>
// user info
private lateinit var gender: DataManager.UserGender
private var birthOfDate: Long = 0L
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.base_user_info_layout, container, false)
activityComponent?.let {
it.inject(this)
mPresenter.onAttach(this)
}
return view
}
override fun onDateSet(dataPicker: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
birthOfDate = GregorianCalendar(year, month, dayOfMonth).timeInMillis
}
}
答案 0 :(得分:1)
在provideDatePickerDialog
中,您需要BasicInfoFragment
,但是当您还尝试在DatePickerDialog
中注入BasicInfoFragment
时。因此鸡或鸡蛋的问题 - 要创造其中任何一个,你需要另一个。
要考虑的其他因素:在DateTimePicker的构造函数中,您确实需要DatePickerDialog.OnDateSetListener
而不是BasicInfoFragment
。
解决方案1
按如下所示更改provideDatePickerDialog
@Provides
fun provideDatePickerDialog(basicInfoFragment: BasicInfoFragment):
DatePickerDialog {
return DatePickerDialog(activity)
}
然后在片段中设置监听器和日期。请参阅文档here
解决方案2
不要为DatePickerDialog提供Dagger,而是使用以下行在BasicInfoFragment中创建它:
DatePickerDialog(activity, this, 1999, 9, 9)
通过这种方式,您还可以消除其他可能的问题和混淆。