在匕首2中找到了依赖循环

时间:2018-02-07 17:21:05

标签: android kotlin dagger-2

我尝试使用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
    }
}

1 个答案:

答案 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)

通过这种方式,您还可以消除其他可能的问题和混淆。