在构造函数Dagger中提供当前活动

时间:2019-03-09 07:02:47

标签: android kotlin dependency-injection dagger-2

我是Dagger的新手,很棒,但是我遇到了问题。

对话框类需要当前活动为context进行初始化。

class ProgressUtil @Inject constructor(val context: Activity) {

    var dialog: Dialog? = null

    fun show() {
        hide()

        dialog = Dialog(context)
        dialog?.let {
            it.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            it.setContentView(R.layout.progress_dialog)
            it.setCancelable(false)
            it.show()
        }
    }

    fun hide() {
        dialog?.let {
            if (it.isShowing) {
                it.dismiss()
            }
        }
    }
}

这是我的ActivityModules

@Module
abstract class ActivityModules {

    @ContributesAndroidInjector
    abstract fun contributeMainActivity() : MainActivity

    @ContributesAndroidInjector
    abstract fun contributePostsActivity() : PostsActivity

    // Want to pass current activity as activity param
    @Provides
    fun progressUtilMainActivity(activity: Activity): ProgressUtil = ProgressUtil(activity)

}

AppComponent类

@Singleton
@Component(
    modules = [
        AndroidSupportInjectionModule::class,
        ActivityModules::class
    ]
)
interface AppComponent {

    @Component.Builder
    interface Builder {

        @BindsInstance
        fun application(application: AppController) : Builder

        fun build() : AppComponent

    }

    fun inject(application: AppController)
}

是否有一种通用方法可以在许多活动中使用进度条,而无需为每个活动创建模块?

0 个答案:

没有答案