Android应用中设置非系统默认语言(使用Kotlin)

以下是使用Kotlin在Android应用中设置非系统默认语言的几种方法:

方法1:通过扩展函数动态更改语言

Kotlin 复制代码
fun Context.setAppLocale(languageCode: String): Context {
    val locale = Locale(languageCode)
    Locale.setDefault(locale)
    
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        updateResourcesLocale(locale)
    } else {
        updateResourcesLocaleLegacy(locale)
    }
}

@RequiresApi(Build.VERSION_CODES.N)
private fun Context.updateResourcesLocale(locale: Locale): Context {
    val configuration = resources.configuration
    configuration.setLocale(locale)
    return createConfigurationContext(configuration)
}

@Suppress("DEPRECATION")
private fun Context.updateResourcesLocaleLegacy(locale: Locale): Context {
    val resources = resources
    val configuration = resources.configuration
    configuration.locale = locale
    resources.updateConfiguration(configuration, resources.displayMetrics)
    return this
}

在Activity中使用:

Kotlin 复制代码
// 设置为法语
val newContext = context.setAppLocale("fr")
// 需要重启Activity使更改生效
recreate()

方法2:在Application类中初始化语言

Kotlin 复制代码
class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        // 从SharedPreferences读取用户选择的语言
        val lang = getPreferredLanguage()
        setAppLocale(lang)
    }
    
    private fun getPreferredLanguage(): String {
        // 从SharedPreferences获取语言设置
        val prefs = PreferenceManager.getDefaultSharedPreferences(this)
        return prefs.getString("app_language", "en") ?: "en"
    }
    
    private fun setAppLocale(languageCode: String) {
        val resources = resources
        val config = resources.configuration
        val locale = Locale(languageCode)
        Locale.setDefault(locale)
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            config.setLocale(locale)
        } else {
            @Suppress("DEPRECATION")
            config.locale = locale
        }
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            createConfigurationContext(config)
        }
        
        @Suppress("DEPRECATION")
        resources.updateConfiguration(config, resources.displayMetrics)
    }
}

方法3:使用BaseActivity管理语言

Kotlin 复制代码
open class BaseActivity : AppCompatActivity() {
    override fun attachBaseContext(newBase: Context) {
        // 从SharedPreferences获取语言设置
        val language = newBase.getPreferredLanguage()
        super.attachBaseContext(newBase.setAppLocale(language))
    }
}

// 然后让所有Activity继承自BaseActivity
class MainActivity : BaseActivity() {
    // ...
}

// SharedPreferences扩展函数
fun Context.getPreferredLanguage(): String {
    val prefs = PreferenceManager.getDefaultSharedPreferences(this)
    return prefs.getString("app_language", "en") ?: "en"
}

切换语言的实用函数

Kotlin 复制代码
fun Activity.changeAppLanguage(languageCode: String) {
    // 保存语言设置
    val prefs = PreferenceManager.getDefaultSharedPreferences(this)
    prefs.edit().putString("app_language", languageCode).apply()
    
    // 更新应用上下文
    val newContext = setAppLocale(languageCode)
    
    // 重启当前Activity
    recreate()
    
    // 如果需要更新所有Activity,可以发送广播通知其他Activity重启
    sendBroadcast(Intent("LANGUAGE_CHANGED"))
}

注意事项

资源文件结构

Kotlin 复制代码
res/
  values/           # 默认资源 (英语)
  values-fr/        # 法语资源
  values-es/        # 西班牙语资源
  values-zh/        # 中文资源

这些方法可以让你在Android应用中独立于系统设置使用特定的语言。

  1. 语言代码格式

    • 使用ISO 639-1语言代码(如"en", "fr", "es")

    • 对于特定地区的变体,可以使用格式如"zh-rCN"(简体中文)、"zh-rTW"(繁体中文)

  2. 兼容性处理

    • 对于Android 7.0及以上版本使用新的API

    • 对于旧版本使用兼容方法

  3. Activity生命周期

    • 更改语言后通常需要重启Activity才能看到效果

    • 可以使用recreate()方法重启当前Activity

  4. 持久化存储

    • 使用SharedPreferences存储用户的语言选择

    • 每次应用启动时读取设置并应用

  5. 这些方法可以让你在Android应用中独立于系统设置使用特定的语言。

Android应用中设置非系统默认语言(java)-CSDN博客

Jetpack Compose 中更新应用语言-CSDN博客

相关推荐
程序员陆业聪15 小时前
从 OpenClaw 到 Android:Harness Engineering 是怎么让 Agent 变得可用的
android
hnlgzb17 小时前
常见的Android Jetpack库会有哪些?这些库中又有哪些常用类的?
android·android jetpack
钛态21 小时前
Flutter 三方库 http_mock_adapter — 赋能鸿蒙应用开发的高效率网络接口 Mock 与自动化测试注入引擎(适配鸿蒙 HarmonyOS Next ohos)
android·网络协议·flutter·http·华为·中间件·harmonyos
王码码203521 小时前
Flutter for OpenHarmony:Flutter 三方库 algoliasearch 毫秒级云端搜索体验(云原生搜索引擎)
android·前端·git·flutter·搜索引擎·云原生·harmonyos
左手厨刀右手茼蒿21 小时前
Flutter for OpenHarmony: Flutter 三方库 shamsi_date 助力鸿蒙应用精准适配波斯历法(中东出海必备)
android·flutter·ui·华为·自动化·harmonyos
代码飞天21 小时前
wireshark的高级使用
android·java·wireshark
2501_915918411 天前
苹果App Store上架审核卡住原因分析与解决方案指南
android·ios·小程序·https·uni-app·iphone·webview
skiy1 天前
MySQL Workbench菜单汉化为中文
android·数据库·mysql
小小小点1 天前
Android四大常用布局详解与实战
android
MinQ1 天前
binder和socket区别及原理
android