Skip to content

Instantly share code, notes, and snippets.

@devqmr
Created January 28, 2019 07:40
Show Gist options
  • Save devqmr/db707c993f4a353e6e00364a5b754f1f to your computer and use it in GitHub Desktop.
Save devqmr/db707c993f4a353e6e00364a5b754f1f to your computer and use it in GitHub Desktop.
ResourceProvider helper class use make access to Android Resource without need to deal with context direct
package com.exa.nanashopper.util
import android.content.Context
import android.content.res.Configuration
import androidx.core.content.ContextCompat
import java.util.*
/**
* ResourceProvider helper class use make access to Android Resource without need to deal with context direct
* That will bw help inside ViewModel classes should not, though, hold a reference to Activities, Fragments, or Contexts
*/
class ResourceProvider(val context: Context) {
/**
* Fetch the String Resource that select by resId then return the equivalent String
* @param resId
*/
fun getString(resId: Int): String {
applyCurrentLanguage()
return context.getString(resId)
}
/**
* Fetch the String Resource that select by resId and the pass value then return the equivalent String
* @param resId
* @param value
*/
fun getString(resId: Int, value: String): String {
applyCurrentLanguage()
return context.getString(resId, value)
}
/**
* Fetch the String Resource that select by resId and the pass value then return the equivalent String
* @param resId
* @param value
*/
fun getString(resId: Int, vararg value: Any): String {
return context.getString(resId, value)
}
/**
* Fetch the String Resource that select by resId and the pass value then return the equivalent String
* @param resId
* @param value1
* @param value2
*/
fun getString(resId: Int, value1: String, value2: String): String {
applyCurrentLanguage()
return context.getString(resId, value1, value2)
}
/**
* Fetch the String Resource that select by resId and the pass value then return the equivalent String
* @param resId
* @param value
*/
fun getString(resId: Int, value: Int): String {
applyCurrentLanguage()
return context.getString(resId, value)
}
/**
* Fetch the String Resource that select by resId and the pass value1 then return the equivalent String
* @param resId
* @param value1
* @param value2
*/
fun getString(resId: Int, value1: Int, value2: Int): String {
applyCurrentLanguage()
return context.getString(resId, value1, value2)
}
/**
* Fetch the Color Resource that select by resId then return the equivalent Color
* @param resId Int color resource Id
* @return Int the color
*/
fun getColor(resId: Int): Int {
return ContextCompat.getColor(context, resId)
}
private fun applyCurrentLanguage() {
val locale = Locale(LanguageUtils.getLanguage())
Locale.setDefault(locale)
val res = context.resources
val config = Configuration(res.configuration)
config.locale = locale
res.updateConfiguration(config, res.displayMetrics)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment