Skip to content

Instantly share code, notes, and snippets.

@ElianFabian
Last active July 20, 2024 12:58
Show Gist options
  • Save ElianFabian/e94071f348998c24bedaa959ddb8df40 to your computer and use it in GitHub Desktop.
Save ElianFabian/e94071f348998c24bedaa959ddb8df40 to your computer and use it in GitHub Desktop.
Snippet to add constants in BuildConfig for default language and supported languages dynamically based on values-* folders. Based on: https://gist.github.com/bleeding182/a7664adbbf087ff0a58967e332a8ed14
import java.util.Locale
// [...]
android {
defaultConfig {
// [...]
val defaultLocale = Locale("en")
val appLocales = getAppLocales(defaultLocale)
val appLanguages = appLocales.joinToString(",") { locale ->
"\"${locale}\""
}
buildConfigField("String", "DEFAULT_LANGUAGE", "\"$defaultLocale\"")
buildConfigField("String[]", "SUPPORTED_LANGUAGES", "new String[]{$appLanguages}")
resourceConfigurations += appLocales.map { it.toString() }
}
}
// [...]
fun getAppLocales(defaultLocale: Locale): List<Locale> {
val foundLocales = mutableListOf(defaultLocale)
project.android.sourceSets.getByName("main").res.srcDirs.forEach { resFolder ->
resFolder.listFiles().orEmpty()
.filter { folder ->
folder.name.startsWith("values-") && !folder.listFiles().isNullOrEmpty()
}
.mapNotNull { valuesFolder ->
val hasStringsXmlFile = valuesFolder.listFiles().orEmpty().filterNotNull().any { file ->
file.name == "strings.xml"
}
if (!hasStringsXmlFile) {
return@mapNotNull null
}
var config = valuesFolder.name.replaceFirst("values-", "").replaceFirst("values", "").let { config ->
if (config.startsWith("mcc") || config.startsWith("mnc")) {
val splitPosition = config.indexOf('-')
if (splitPosition >= 0) {
return@let config.substring(splitPosition + 1)
}
}
return@let config
}
runCatching {
val locale = if (config.startsWith("b+")) {
val splitPosition = config.indexOf('-')
if (splitPosition >= 0) {
config = config.substring(0, splitPosition)
}
Locale.forLanguageTag(config.substring(2))
}
else {
val parts = config.split('-')
if (parts.size == 1 || !parts[1].startsWith('r')) {
Locale(parts[0])
}
else Locale(parts[0], parts[1].substring(1))
}
if (locale.isO3Language != null) {
foundLocales.add(locale)
}
}
}
}
return foundLocales
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment