-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c0c7a7b
commit c2e0665
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
43 changes: 43 additions & 0 deletions
43
core/src/main/java/com/kylecorry/andromeda/core/system/ResourceCache.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
package com.kylecorry.andromeda.core.system | ||
|
||
import android.content.res.Resources | ||
import android.os.Build | ||
import java.util.* | ||
|
||
class ResourceCache(private val resources: Resources) { | ||
|
||
private var lastLocale = getLocale() | ||
private val cache = mutableMapOf<Int, String>() | ||
private val lock = Any() | ||
|
||
fun getString(id: Int): String { | ||
synchronized(lock) { | ||
val currentLocale = getLocale() | ||
if (lastLocale != currentLocale) { | ||
cache.clear() | ||
lastLocale = currentLocale | ||
} | ||
|
||
if (cache.containsKey(id)) { | ||
return cache[id]!! | ||
} | ||
val string = resources.getString(id) | ||
cache[id] = string | ||
return string | ||
} | ||
} | ||
|
||
fun getString(id: Int, vararg formatArgs: Any): String { | ||
val raw = getString(id) | ||
return String.format(lastLocale, raw, *formatArgs) | ||
} | ||
|
||
private fun getLocale(): Locale { | ||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { | ||
resources.configuration.locales[0] | ||
} else { | ||
@Suppress("DEPRECATION") | ||
resources.configuration.locale | ||
} | ||
} | ||
} |