Dagger注入片段的对象为空

时间:2019-02-27 20:33:24

标签: java android kotlin dagger-2

我不知道为什么注入后我的对象Coffee为空。在Java代码中,相同的代码也起作用。

类应用程序:

    @Singleton
    @Component(modules = [AndroidSupportInjectionModule::class, ContributesBuilder::class,
    FirstModule::class])
    interface ApplicationComponent {

        @Component.Builder
        interface Builder{


     @BindsInstance
        fun application(application: Application): Builder
        fun build(): ApplicationComponent
    }

    fun inject(app: LocationPickerApplication)
}

提供课程:

@Module
abstract class ContributesBuilder{

    @ContributesAndroidInjector
    abstract fun bindFirstFragment(): FirstFragment

    @ContributesAndroidInjector
    abstract fun bindSecondFragment(): SecondFragment

}

我的带有回咖啡的模块

@Module
class FirstModule {

    @Provides
    fun getCoffee(): Coffee{
        return Coffee()
    }

}

和咖啡课:

class Coffee (name: String = "name")

这有什么问题吗?

这是我的片段,这里的咖啡为空:

class FirstFragment : Fragment() {

    @Inject
    lateinit var coffee: Coffee

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        Toast.makeText(activity, "a $coffee", Toast.LENGTH_LONG).show()

    }

    companion object {
        @JvmStatic
        fun newInstance() =
            FirstFragment()
    }
}

浪费太多时间,我仍然不知道怎么了

1 个答案:

答案 0 :(得分:0)

缺少

int64_t