Android 多语言 切换

你还在重写attachBaseContext自定义多语言切换吗?
你还需要自己用轻量级存储(SharedPreferences、datastore)之类的来保存你切换的语言吗?
你还需要自己编写重启活动逻辑吗?
比如:

override fun attachBaseContext(newBase: Context?) {
        if(newBase==null) {
            super.attachBaseContext(newBase)
            return
        }
        val sp = newBase.getSharedPreferences("share_data", Context.MODE_PRIVATE)
        val language = sp.getString("language", Locale.getDefault().language)
        var locale = Locale.getDefault()
        if (language.equals("en", ignoreCase = true)) {
            locale = Locale.ENGLISH
        } else if (language.equals("ko", ignoreCase = true)) {
            locale = Locale.KOREA
        } else if (language.equals("zh", ignoreCase = true)) {
            locale = Locale.SIMPLIFIED_CHINESE
        } else if (language.equals("zh_TW", ignoreCase = true)) {
            locale = Locale.TRADITIONAL_CHINESE
        } else if (language.equals("ja", ignoreCase = true)) {
            locale = Locale.JAPAN
        } else if (language.equals("de", ignoreCase = true)) {
            locale = Locale.GERMANY
        } else if (language.equals("pt", ignoreCase = true)) {
            locale = Locale("pt")
        } else if (language.equals("es", ignoreCase = true)) {
            locale = Locale("es")
        } else if (language.equals("fr", ignoreCase = true)) {
            locale = Locale.FRENCH
        } else if (language.equals("ru", ignoreCase = true)) {
            locale = Locale("ru")
        } else if (language.equals("it", ignoreCase = true)) {
            locale = Locale.ITALY
        }
        Log.d("TAG", "changeAppLanguage: $language")
        val metrics = newBase.resources.displayMetrics
        val configuration = newBase.resources.configuration
        configuration.setLocale(locale)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            super.attachBaseContext(newBase.createConfigurationContext(configuration));
        } else {
            newBase.resources.updateConfiguration(configuration, metrics);
            super.attachBaseContext(newBase)
        }

各应用语言偏好设定  |  Android 开发者  |  Android Developers
大体来说就三步

  • 将受支持的语言添加到系统设置 localeConfig="@xml/locale_configs"
    
        ...
        
        
    
    
    
       使用“英语(美国)”作为最终回退语言区域
        英语(英国)
        法语
        日语
        中文(简体,澳门)
        中文(繁体,澳门)
    
  • 注册自动存储的语言服务
    
        
      
      ...
    

使用

        // 使用AndroidX支持库获取当前的应用程序语言环境
        val currentLocaleName = if (!AppCompatDelegate.getApplicationLocales().isEmpty) {
            // 从列表中获取当前的应用程序区域设置
            AppCompatDelegate.getApplicationLocales()[0]?.displayName
        } else {
            // 获取默认的系统区域设置
            Locale.getDefault().displayName
        }

        // 语言设置为“西班牙雨”
        xxx.setOnClickListener {
            val localeList = LocaleListCompat.forLanguageTags("es")
            AppCompatDelegate.setApplicationLocales(localeList)
        }

你可能感兴趣的:(android,kotlin)