android切换语言

首先需要在在Manifest 中通过添加 supportsRtl=true 来声明你的应用支持RTL。

supportsRtl="true" 的唯一作用是:

👉 允许系统在 RTL 语言下,把整个应用的 layoutDirection 从 LTR 切到 RTL

不做任何"自动镜像"之外的事 ,也 不会单独改变文字内容

1️⃣ 没有 supportsRtl 会发生什么?

Kotlin 复制代码
<application
    android:supportsRtl="false">

或默认没写(默认就是 false

当系统语言切到阿拉伯语 / 希伯来语时:

项目 结果
Locale.language ar
Configuration.layoutDirection 仍然是 LTR
start / end left / right 处理
整体布局 不会镜像

写了 supportsRtl="true" 会发生什么?

Kotlin 复制代码
<application
    android:supportsRtl="true">
项目 结果
Locale.language ar
Configuration.layoutDirection RTL
start / end 自动翻转
layout_marginStart 变成右边
Gravity.START 右对齐

3️⃣ 它到底"帮你干了什么"?

✅ 它只影响这一件事

是否允许系统把 layoutDirection 切为 RTL

更新语言代码

Kotlin 复制代码
 fun updateLanguage(context: Context?): Context? {
    var newContext = context ?: return null
    try {
      val language = getLanguage()
      val locale = Locale(language)
      val resources = context.resources
      val configuration = resources.configuration
      configuration.setLocale(locale)
      configuration.fontScale = 1f
      newContext = context.createConfigurationContext(configuration)
      val metrics = resources.displayMetrics
      resources.updateConfiguration(configuration, metrics)
      resources.flushLayoutCache()
    } catch (e: Exception) {
      logEForUtil(logTag, e)
    }
    return newContext
  }

configuration.setLocale(locale)的里面会同时修改布局的方向

代码如下:

复制代码
public void setLocales(@Nullable LocaleList locales) {
    mLocaleList = locales == null ? LocaleList.getEmptyLocaleList() : locales;
    locale = mLocaleList.get(0);
    setLayoutDirection(locale); //修改布局
}
相关推荐
饭小猿人11 小时前
Android 腾讯X5WebView如何禁止系统自带剪切板和自定义剪切板视图
android·java
_李小白11 小时前
【android opencv学习笔记】Day 8: remap(像素位置重映射)
android·opencv·学习
美狐美颜SDK开放平台11 小时前
多场景美颜SDK解决方案:直播APP(iOS/安卓)开发接入详解
android·人工智能·ios·音视频·美颜sdk·第三方美颜sdk·短视频美颜sdk
嗷o嗷o12 小时前
Android BLE 里,MTU、分包和长数据发送到底该怎么处理
android
Gary Studio13 小时前
Android AIDL HAL工程结构示例
android
y = xⁿ14 小时前
MySQL八股知识合集
android·mysql·adb
andr_gale14 小时前
04_rc文件语法规则
android·framework·aosp
祖国的好青年15 小时前
VS Code 搭建 React Native 开发环境(Windows 实战指南)
android·windows·react native·react.js
黄林晴16 小时前
警惕!AGP 9.2 别只改版本号,R8 规则与构建链路全线收紧
android·gradle