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); //修改布局
}
相关推荐
.痞老板.5 小时前
mysql初阶--数据类型
android·数据库·mysql
StarsGreen5 小时前
Android 启动流程详解
android·linux·单片机·嵌入式硬件
booboosui1 天前
Android 上来电怎么判:7 个条件加 5 个中文词
android
MardaWang1 天前
App 内嵌 H5 的信任边界设计(ArkWeb/HarmonyOS 实战)
android
石头慢慢说1 天前
不写 XPath,让 AI 在真机上跑测试:Appium MCP 全流程实战
android
90后的晨仔1 天前
解决 Android 构建报错:Unable to delete file .../file-map.txt
android·前端
mg6681 天前
安卓玩机工具----安卓手机变成桌面电脑!多窗口镜像+音频投射+游戏操控,无需 Root
android·智能手机·电脑
peakmain91 天前
异常处理 - Native 层的崩溃捕获机制及实现 (一)
android·性能优化
木头左1 天前
【Android】听写播放器改版:中英文书写速度拆项与「正在读」高亮
android·room·media3·jetpack compose·听写