Karamba
Karamba

Reputation: 159

How can I use Dagger 2 with custom view?

I read documentation and found, that I can inject Activity objects with "HasActivityInjector" and Fragment objects with "HasFragmentInjector", but how can inject View objects? Like I have custom view instead fragment, how can inject in it?

Upvotes: 4

Views: 1404

Answers (1)

A. Shevchuk
A. Shevchuk

Reputation: 2169

You can declare inject method inside of your component like

fun inject(view: YourCustomView)

and then, when you are using your view on some activity or fragment, call

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        yourCustomView.inject(component)
}

component could be obtained inside fragment's\activity's onCreate from your injection.

On your view you need to implement inject method like this:

fun inject(component: Component) {
        component.inject(this)
    }

That's all, now you can inject everything from your component inside of your custom view.

Upvotes: 1

Related Questions