Skip to content

Instantly share code, notes, and snippets.

@cuber5566
Created January 18, 2018 09:46
Show Gist options
  • Save cuber5566/c40a56893cb332415d83e444438b7664 to your computer and use it in GitHub Desktop.
Save cuber5566/c40a56893cb332415d83e444438b7664 to your computer and use it in GitHub Desktop.
/**
* Provides resources without context.
* should be initial when [Application.onCreate]
*/
@SuppressLint("StaticFieldLeak")
class ResourceProvider(
private var resources: Resources
) : AppResource {
fun application(): Application = APPLICATION!!
override fun resources(): Resources = resources
override fun getString(stringRes: Int): String = resources.getString(stringRes)
override fun getColor(@ColorRes colorRes: Int): Int = ContextCompat.getColor(APPLICATION!!, colorRes)
override fun getDrawable(@DrawableRes drawableRes: Int): Drawable = ContextCompat.getDrawable(APPLICATION!!, drawableRes)!!
companion object {
private var APPLICATION: Application? = null
private var INSTANCE: ResourceProvider? = null
private var RESOURCES: Resources? = null
@JvmStatic
fun init(application: Application) {
APPLICATION = application
RESOURCES = application.resources
}
@JvmStatic
fun getInstance(): ResourceProvider {
return INSTANCE ?: ResourceProvider(
resources = RESOURCES!!
).apply { INSTANCE = this }
}
@VisibleForTesting
fun destroyInstance() {
INSTANCE = null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment