Skip to content
This repository was archived by the owner on Nov 1, 2021. It is now read-only.

Commit e15f902

Browse files
authored
close #24: localize method improved (#25)
Now the method follows [official](https://developer.android.com/guide/topics/resources/multilingual-support) documentations how to resolve resources
1 parent 9a7e371 commit e15f902

File tree

1 file changed

+28
-10
lines changed
  • app-core/src/main/java/com/codee/app/core/extensions

1 file changed

+28
-10
lines changed

app-core/src/main/java/com/codee/app/core/extensions/Localized.kt

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,39 @@ package com.codee.app.core.extensions
22

33
import androidx.core.os.ConfigurationCompat
44
import com.codee.app.core.ContextDI.context
5+
import com.codee.app.resources.locale.Locale
56
import com.codee.app.resources.locale.Localized
67
import com.codee.app.resources.locale.get
78

9+
10+
/**
11+
* First it checks for full equality (languageCode and countryCode), then if there is no such a
12+
* string, it searches for string with the same languageCode but without countryCode specified.
13+
* Then the it tries to get just any string with the languageCode
14+
*
15+
* It repeats with all available locales and finally uses default variant as fallback
16+
*/
817
fun <T> Localized<T>.localize(): T {
9-
val locale = ConfigurationCompat
10-
.getLocales(context.resources.configuration)[0]
11-
.toCodeeLocale()
18+
// getLocales returns custom class, not list
19+
val locales = mutableListOf<Locale>().apply {
20+
val list = ConfigurationCompat.getLocales(context.resources.configuration)
21+
for(i in 1..list.size())
22+
add(list[i].toCodeeLocale())
23+
}
1224

13-
val variants = variants.toList()
25+
for(locale in locales) {
26+
val languageCodeMatches = variants
27+
.filter { (k) -> k.languageCode == locale.languageCode }
28+
val countryCodeMatches = languageCodeMatches
29+
.filter { (k) -> k.countryCode == locale.countryCode }
1430

15-
val withLanguageCode = variants
16-
.filter { (k) -> k.languageCode == locale.languageCode }
31+
val result = countryCodeMatches.values.firstOrNull()
32+
?: languageCodeMatches.filter { (k) -> k.countryCode == null }.values.firstOrNull()
33+
?: languageCodeMatches.values.firstOrNull()
1734

18-
val withCountryCode = withLanguageCode
19-
.firstOrNull { (k) -> k.countryCode == locale.countryCode }
35+
if(result != null)
36+
return result
37+
}
2038

21-
return (withCountryCode ?: withLanguageCode.firstOrNull())?.second ?: default
22-
}
39+
return default
40+
}

0 commit comments

Comments
 (0)