@@ -4,15 +4,36 @@ import android.content.Context
44import java.lang.Exception
55import java.lang.StringBuilder
66import java.util.*
7+ import android.content.res.Configuration
8+ import android.content.res.Resources
9+ import java.io.File
710
811// 从Resource解析字符串,实现输出内容多语言
912class ShellTranslation (val context : Context ) {
1013 // 示例:
1114 // @string:home_shell_01
12- private val regex1 = Regex (" ^ @(string|dimen):[_a-z]+.* " , RegexOption .IGNORE_CASE )
15+ private val regex1 = Regex (" @(string|dimen):[_a-z][_0-9a-z]+ " , RegexOption .IGNORE_CASE )
1316 // 示例
1417 // @string/home_shell_01
15- private val regex2 = Regex (" ^@(string|dimen)/[_a-z]+.*" , RegexOption .IGNORE_CASE )
18+ private val regex2 = Regex (" @(string|dimen)/[_a-z][_0-9a-z]+" , RegexOption .IGNORE_CASE )
19+
20+ private val appResources: Resources by lazy {
21+ runCatching {
22+ val langFile = File (context.filesDir, " home/log/language" )
23+ val lang = langFile
24+ .takeIf { it.exists() }
25+ ?.readText()
26+ ?.trim()
27+ ?.takeIf { it.isNotEmpty() }
28+ ? : return @runCatching context.resources
29+ val locale = Locale .forLanguageTag(lang.replace(" _" , " -" ))
30+ val config = Configuration (context.resources.configuration)
31+ config.setLocale(locale)
32+ context.createConfigurationContext(config).resources
33+ }.getOrElse {
34+ context.resources
35+ }
36+ }
1637
1738 fun resolveRow (originRow : String ): String {
1839 val separator = if (regex1.matches(originRow)) {
@@ -24,7 +45,8 @@ class ShellTranslation(val context: Context) {
2445 }
2546 if (separator != null ) {
2647 val row = originRow.trim()
27- val resources = context.resources
48+ // val resources = context.resources
49+ val resources = appResources
2850 val type = row.substring(1 , row.indexOf(separator)).lowercase(Locale .ENGLISH )
2951 val name = row.substring(row.indexOf(separator) + 1 )
3052
0 commit comments