适配中英文切换

This commit is contained in:
2026-05-08 16:39:15 +08:00
parent 428b5e507f
commit 5ee50d3785
38 changed files with 1248 additions and 191 deletions

View File

@@ -0,0 +1,115 @@
package com.example.defenseapplication.utils
import android.content.Context
import android.content.SharedPreferences
import android.content.res.Configuration
import android.content.res.Resources
import android.os.Build
import android.os.LocaleList
import java.util.Locale
object LanguageUtil {
private const val PREF_NAME = "language_pref"
private const val KEY_LANGUAGE = "selected_language"
const val LANGUAGE_CHINESE = "zh"
const val LANGUAGE_ENGLISH = "en"
/**
* 切换语言
* @param context 上下文
* @param language 语言代码: "zh" 中文, "en" 英文
*/
fun switchLanguage(context: Context, language: String) {
saveLanguage(context, language)
}
/**
* 获取当前设置的语言
*/
fun getCurrentLanguage(context: Context): String {
val prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
return prefs.getString(KEY_LANGUAGE, LANGUAGE_CHINESE) ?: LANGUAGE_CHINESE
}
/**
* 保存语言设置
*/
private fun saveLanguage(context: Context, language: String) {
val prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
prefs.edit().putString(KEY_LANGUAGE, language).apply()
}
/**
* 判断当前是否是中文
*/
fun isChinese(context: Context): Boolean {
return getCurrentLanguage(context) == LANGUAGE_CHINESE
}
/**
* 获取本地化的 Context用于在应用内切换语言
* 在 attachBaseContext 中调用
*/
fun attachBaseContext(context: Context): Context {
val language = getCurrentLanguage(context)
return createLocalizedContext(context, language)
}
/**
* 创建本地化的 Context
*/
private fun createLocalizedContext(context: Context, language: String): Context {
val locale = Locale(language)
Locale.setDefault(locale)
val resources = context.resources
val configuration = resources.configuration
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// Android 7.0 及以上
val localeList = LocaleList(locale)
configuration.setLocales(localeList)
context.createConfigurationContext(configuration)
} else {
// Android 7.0 以下
configuration.locale = locale
resources.updateConfiguration(configuration, resources.displayMetrics)
context
}
}
/**
* 更新应用语言(用于在 Activity 中动态切换)
*/
fun updateResources(context: Context): Context {
val language = getCurrentLanguage(context)
val locale = Locale(language)
Locale.setDefault(locale)
val resources = context.resources
val configuration = resources.configuration
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val localeList = LocaleList(locale)
configuration.setLocales(localeList)
} else {
configuration.locale = locale
}
resources.updateConfiguration(configuration, resources.displayMetrics)
return context
}
/**
* 获取语言显示名称
*/
fun getLanguageDisplayName(language: String): String {
return when (language) {
LANGUAGE_CHINESE -> "中文"
LANGUAGE_ENGLISH -> "English"
else -> "中文"
}
}
}