kotlin compose 实现应用内多语言切换(不重新打开App)

1. 示例图

2.具体实现

如何实现上述示例,且不需要重新打开App

①自定义 MainApplication  实现 Application ,定义两个变量:

class MainApplication : Application() {

     object GlobalDpData {
        var language: String = ""
        var defaultLanguage: String = "en"
    }
    override fun onCreate() {
        defaultLanguage = Locale.getDefault().language 
        val cacheLanguage = "保存在手机App本地的切换后的语言,可用sp或文件实现" 
        language = if (cacheLanguage.isNullOrEmpty()) { 
            defaultLanguage 
        } else  { 
            cacheLanguage 
        }
     }
}

②在baseActivity中添加语言实现

override fun attachBaseContext(baseContext: Context) {
    var language = MainApplication.GlobalDpData.language
    if (language.isEmpty()) {
        val default = MainApplication.GlobalDpData.defaultLanguage
        language = "保存在手机App本地的切换后的语言,可用sp或文件实现" 
    }
    // 创建一个ContextWrapper对象
    val context = newWrap(baseContext, language)
    // 将新的的Context设置给Activity
    super.attachBaseContext(context)
}
/**
 *  创建ContextWrapper对象,
 */
private fun newWrap(context: Context, language: String): ContextWrapper {
    val configuration = context.resources.configuration
    configuration.fontScale = 1f
    val locale = Locale(language)
    val localeList = LocaleList(locale)
    LocaleList.setDefault(localeList)
    configuration.setLocales(localeList)
    

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-20 21:04:01       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-20 21:04:01       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-20 21:04:01       45 阅读
  4. Python语言-面向对象

    2024-07-20 21:04:01       55 阅读

热门阅读

  1. C++中size_t怎么用

    2024-07-20 21:04:01       14 阅读
  2. Linux CAN数据收发

    2024-07-20 21:04:01       16 阅读
  3. shell + Python3 | 解析理解 gencode gtf 基因组注释文件

    2024-07-20 21:04:01       14 阅读
  4. dockerfile

    2024-07-20 21:04:01       16 阅读
  5. 一周速递|全球车联网产业动态(2024年7月21日)

    2024-07-20 21:04:01       17 阅读
  6. 好文推荐与一句话的答案

    2024-07-20 21:04:01       17 阅读