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); //修改布局
}
相关推荐
BoomHe1 天前
Android AOSP13 原生 Launcher3 壁纸获取方式
android
Digitally1 天前
如何将联系人从 Android 转移到 Android
android
李小枫1 天前
webflux接收application/x-www-form-urlencoded参数
android·java·开发语言
爱丽_1 天前
MySQL `EXPLAIN`:看懂执行计划、判断索引是否生效与排错套路
android·数据库·mysql
NPE~1 天前
[App逆向]环境搭建下篇 — — 逆向源码+hook实战
android·javascript·python·教程·逆向·hook·逆向分析
yewq-cn1 天前
AOSP 下载
android
cch89181 天前
Laravel vs ThinkPHP:PHP框架终极对决
android·php·laravel
米码收割机1 天前
【Android】基于安卓app的汽车租赁管理系统(源码+部署方式+论文)[独一无二]
android·汽车
流星雨在线1 天前
安卓使用 Startup 管理三方 SDK 初始化
android·startup
jwn9991 天前
Laravel3.x:PHP框架的经典里程碑
android