Search code examples
androidkotlindagger

“dagger-android” library, how to inject a property of a Dialog class?


I followed the example which claims that is the better "new way". (https://proandroiddev.com/exploring-the-new-dagger-android-module-9eb6075f1a46) The full sample source code is here (https://github.com/jshvarts/DaggerAndroidKotlinSampleApp). It uses this to inject properties to an Activity like this,

class MainActivity:AppCompatActivity()
{
    @Inject
    lateinit var something:Something

    override fun onCreate(..)
    {
      AndroidInjection.inject(this)
      ...

And a module

@Module
abstract class ActivitiesModule
{
    @ContributesAndroidInjector
    abstract fun bindMainActivity():MainActivity

It works well, but what about a custom Dialog class? I create the Dialog with some custom arguments (which are only known at run-time with user's inputs) like the following. I may modify the constructor of MyDialog to take something, and let the activity eventually pass something to the MyDialog's constructor.

But it would be ugly, because the activity does not directly create MyDialog. MainActivity has a custom control, and that custom control shows MyDialog when a button is clicked on it. So, to use the constructor method, I must pass something from MainActivity to the custom control, and then let the custom control create MyDialog with something.

class MyDialog:Dialog
{
      @Inject
      lateinit var something:Something

      constructor(context:Context?, arg1, args2, args3):super(context)
      {
          //Cannot call AndroidInjection.inject, because
          //it does not take a Dialog.
          AndroidInjection.inject(this); //<--Does NOT work.

If only I could tell Dagger to inject the fields of MyDialog at its constructor... What is the solution for this?


Solution

  • AndroidInjection only works on the classes like activities and fragments, not dialogs. If you want to inject your dialog, use a dialog fragment instead. Or, since you can actually just call the constructor, use constructor injection and not Dagger.