Skip to content

Instantly share code, notes, and snippets.

@er-abhishek-luthra
Last active August 22, 2019 14:34
Show Gist options
  • Save er-abhishek-luthra/3136a76f861afc22eb2983ddde840b2b to your computer and use it in GitHub Desktop.
Save er-abhishek-luthra/3136a76f861afc22eb2983ddde840b2b to your computer and use it in GitHub Desktop.
ApplicationInjector - Android Dagger 2 Helper class to automatically inject fragments if they implement [Injectable].
package com.chargingwatts.di
import android.app.Activity
import android.app.Application
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import com.chargingwatts.ChargingApp
import dagger.android.AndroidInjection
import dagger.android.support.AndroidSupportInjection
import dagger.android.support.HasSupportFragmentInjector
/**
* Helper class to automatically inject fragments if they implement [Injectable].
*/
object ApplicationInjector {
@JvmStatic
fun init(goibiboApplication: GoibiboApplication) {
DaggerAppComponent.builder().application(goibiboApplication)
.build().inject(goibiboApplication)
goibiboApplication
.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
handleActivity(activity)
}
override fun onActivityStarted(activity: Activity) {
}
override fun onActivityResumed(activity: Activity) {
}
override fun onActivityPaused(activity: Activity) {
}
override fun onActivityStopped(activity: Activity) {
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle?) {
}
override fun onActivityDestroyed(activity: Activity) {
}
})
}
private fun handleActivity(activity: Activity) {
if (activity is HasSupportFragmentInjector) {
AndroidInjection.inject(activity)
}
if (activity is FragmentActivity) {
activity.supportFragmentManager
.registerFragmentLifecycleCallbacks(
object : FragmentManager.FragmentLifecycleCallbacks() {
override fun onFragmentCreated(
fm: FragmentManager,
f: Fragment,
savedInstanceState: Bundle?
) {
if (f is Injectable) {
AndroidSupportInjection.inject(f)
}
}
}, true
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment