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); //修改布局
}
相关推荐
a59865228 分钟前
Docker多开云手机,六边云独立端口隔离访问实战
android·运维·docker·容器·智能手机·云手机
峥嵘life1 小时前
Android16 开机后立即打开相机闪退问题分析与解决总结
android·开发语言·数码相机·策略模式
用户2018792831671 小时前
从点击图标到首帧"上菜":一篇吃透 Android 启动优化原理
android
镜象科技2 小时前
职业院校AI心理健康解决方案是什么?从一台设备到全周期守护
android·人工智能
码上有光2 小时前
Linux:信号的认识、信号的产生、信号的保存、信号的处理
android·linux·运维·信号
silvamux_3 小时前
4款新模型商务邮件翻译横评:0.98到0.46
android·java·javascript
ynchyong4 小时前
创建MySQL只读账号
android·数据库·mysql
朱涛的自习室14 小时前
我给 Gemini 4 和 DeepSeek 搞了套「末位淘汰」,AI 干活会更猛吗?(Day 3)
android·前端·后端