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); //修改布局
}
相关推荐
booboosui5 小时前
清单 40 件是硬上限:过期的活挂了 48 小时才被打标记
android
FlightYe6 小时前
linux系统编程(二十一):C 语言常见坑
android·linux·运维·服务器·c语言·音视频
方白羽7 小时前
SP vs DataStore:解锁 Android 本地存储的并发秘密
android·app·客户端
GY-937 小时前
【Android】View和Componse
android
王二蛋与他的张大花8 小时前
后台内存 827MB,我一行业务逻辑都没改就砍到 100MB
android·flutter·性能优化
Paper_Love9 小时前
android安全公告网站
android
StarsGreen12 小时前
Android ADB(Android Debug Bridge)命令详解
android
阿健君13 小时前
现代 Android 屏幕适配完全指南
android·kotlin
软件交付观察室15 小时前
用户关掉手机定位权限后,原生App还能显示哪些位置?
android·ios·移动开发
黄林晴15 小时前
Jetpack Compose 1.13.0 来了:大量 API 弃用,表单代码要重构
android·android jetpack