網站首頁 編程語言 正文
快速定位與修復
修改記錄 | 修改時間 |
---|---|
新建 | 2021.01.09 |
出現問題時的調用方式:
public class I18nBaseActivity extends AppCompatActivity { @Override protected void attachBaseContext(Context newBase) { //切換多語言,然后將新生成的 context 覆蓋給 attachBaseContext() Context context = MultiLanguageUtils.changeContextLocale(newBase); super.attachBaseContext(context); } }
解決方法:
Androidx(appcompat:1.2.0) 中對attachBaseContext()
包裝了一層ContextThemeWrapper
,但就是因為他給包的這一層邏輯有問題,導致了多語言切換時效。所以咱們手動給包一層
public class I18nBaseActivity extends AppCompatActivity { @Override protected void attachBaseContext(Context newBase) { //切換多語言,然后將新生成的 context 覆蓋給 attachBaseContext() Context context = MultiLanguageUtils.changeContextLocale(newBase); //兼容appcompat 1.2.0后切換語言失效問題 final Configuration configuration = context.getResources().getConfiguration(); final ContextThemeWrapper wrappedContext = new ContextThemeWrapper(context, R.style.Base_Theme_AppCompat_Empty) { @Override public void applyOverrideConfiguration(Configuration overrideConfiguration) { if (overrideConfiguration != null) { overrideConfiguration.setTo(configuration); } super.applyOverrideConfiguration(overrideConfiguration); } }; super.attachBaseContext(wrappedContext); } }
封裝
上面僅說明了怎么解決問題,沒有體現多語言切換的實現。所以我封裝了一個庫(實質就是一個工具類),該庫已經適配了該問題,大家可以直接copy出來使用
Github : github.com/StefanShan/…
詳細排查過程與原理
最近項目升級為 Androidx,發現之前的多語言切換失效了。經過一點點排除方式排查,發現是由于升到 Androidx 后項目引入了 androidx.appcompat:appcompat:1.2.0
來替代之前的v7
包。那么根據多語言切換原理來看看是什么原因。
多語言切換原理:修改 context 的 Locale 配置,將新生成的 context 設置給 attachBaseContext 實現配置的替換。
先來看下 androidx 下的 AppCompatActivity# attachBaseContext() 源碼
@Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(getDelegate().attachBaseContext2(newBase)); }
哦~ 有個代理類處理了傳入的 context,看下這個代理類 getDelegate()
的attachBaseContext2()
/** * @return The {@link AppCompatDelegate} being used by this Activity. */ @NonNull public AppCompatDelegate getDelegate() { if (mDelegate == null) { mDelegate = AppCompatDelegate.create(this, this); //代理對象是通過 AppCompatDelegate create出來的,那繼續往下看 } return mDelegate; }
// 這里直接看 AppCompatDelegateImpl 類,該類是 AppCompatDelegate 類的實現類 @NonNull @Override @CallSuper public Context attachBaseContext2(@NonNull final Context baseContext) { //...... /** * 這段邏輯是:如果傳入的 context 是經過 ContextThemeWrapper 封裝的,則直接使用該 context 配置進行覆蓋 */ // If the base context is a ContextThemeWrapper (thus not an Application context) // and nobody's touched its Resources yet, we can shortcut and directly apply our // override configuration. if (sCanApplyOverrideConfiguration && baseContext instanceof android.view.ContextThemeWrapper) { final Configuration config = createOverrideConfigurationForDayNight( baseContext, modeToApply, null); if (DEBUG) { Log.d(TAG, String.format("Attempting to apply config to base context: %s", config.toString())); } try { ContextThemeWrapperCompatApi17Impl.applyOverrideConfiguration( (android.view.ContextThemeWrapper) baseContext, config); return baseContext; } catch (IllegalStateException e) { if (DEBUG) { Log.d(TAG, "Failed to apply configuration to base context", e); } } } // ...... /** * 下面這段邏輯是:通過 packageManger 獲取配置,然后和傳入的 context 配置進行對比,覆蓋修改過的配置。 * 這里有個關鍵因素,通過 packageManager 獲取的配置與 context 的配置進行 diff 更新,并將 diff 結果賦值給新建的 configration。這就會導致,當這一次切換成功后,殺死進程下次啟動時,由于 packageManager 配置的語言 與 context 配置的語言一致,而直接跳過,并沒有給新建的 configration進行賦值。最終導致多語言切換失效。同理,從 ActivityA 設置了多語言,然后重啟 ActivityA,再從ActivityA 跳轉到 ActivityB,此時ActivityB 多語言并沒有生效。 */ // We can't trust the application resources returned from the base context, since they // may have been altered by the caller, so instead we'll obtain them directly from the // Package Manager. final Configuration appConfig; try { appConfig = baseContext.getPackageManager().getResourcesForApplication( baseContext.getApplicationInfo()).getConfiguration(); } catch (PackageManager.NameNotFoundException e) { throw new RuntimeException("Application failed to obtain resources from itself", e); } // The caller may have directly modified the base configuration, so we'll defensively // re-structure their changes as a configuration overlay and merge them with our own // night mode changes. Diffing against the application configuration reveals any changes. final Configuration baseConfig = baseContext.getResources().getConfiguration(); final Configuration configOverlay; if (!appConfig.equals(baseConfig)) { configOverlay = generateConfigDelta(appConfig, baseConfig); //這里是關鍵 if (DEBUG) { Log.d(TAG, "Application config (" + appConfig + ") does not match base config (" + baseConfig + "), using base overlay: " + configOverlay); } } else { configOverlay = null; if (DEBUG) { Log.d(TAG, "Application config (" + appConfig + ") matches base context " + "config, using empty base overlay"); } } final Configuration config = createOverrideConfigurationForDayNight( baseContext, modeToApply, configOverlay); if (DEBUG) { Log.d(TAG, String.format("Applying night mode using ContextThemeWrapper and " + "applyOverrideConfiguration(). Config: %s", config.toString())); } // Next, we'll wrap the base context to ensure any method overrides or themes are left // intact. Since ThemeOverlay.AppCompat theme is empty, we'll get the base context's theme. final ContextThemeWrapper wrappedContext = new ContextThemeWrapper(baseContext, R.style.Theme_AppCompat_Empty); wrappedContext.applyOverrideConfiguration(config); // ...... return super.attachBaseContext2(wrappedContext); }
@NonNull private static Configuration generateConfigDelta(@NonNull Configuration base, @Nullable Configuration change) { final Configuration delta = new Configuration(); delta.fontScale = 0; //...... //這里可以看到,如果兩個配置相等,則直接跳過了,并沒有給新創建的 delta 的 locale 賦值。 if (Build.VERSION.SDK_INT >= 24) { ConfigurationImplApi24.generateConfigDelta_locale(base, change, delta); } else { if (!ObjectsCompat.equals(base.locale, change.locale)) { delta.locale = change.locale; } } //...... }
Ok,上面注釋已經非常清晰了。這里簡單總結下:
AppCompatActivity# attachBaseContext()
方法在 Androidx 進行了包裝,具體實現在 AppCompatDelegateImpl# attachBaseContext2()
。
該包裝方法實現了兩套邏輯:
傳入的 context 是經過 ContextThemeWrapper 封裝的,則直接使用該 context 配置(包含語言)進行覆蓋
傳入的 context 未經過 ContextThemeWrapper 封裝,則從 PackageManger 中獲取配置(包含語言),然后和傳入的 context 配置(包含語言)進行對比,并新創建了一個 configration 對象,如果兩者有對比不同的配置則賦值給這個 configration,如果相同則跳過,最后將這個新建的 configration 作為最終配置結果進行覆蓋。
而多語言問題就出現在 [2] 這套邏輯上,如果 PackageManager 與 傳入的 context 某個配置項一致時就不會給新建的 configration 賦值該配置項。這就會導致當這一次切換成功后,殺死進程下次啟動時,由于 packageManager 配置的語言 與 context 配置的語言一致,而直接跳過,并沒有給新建的 configration進行賦值,最終表現就是多語言失效。
原文鏈接:https://juejin.cn/post/6915751118416904199
相關推薦
- 2022-04-26 MFC修改編輯框光標顯示位置方法詳解_C 語言
- 2022-11-26 Linux?top命令詳解_linux shell
- 2022-01-04 圖片網絡地址轉base64和文件
- 2022-03-10 .NET6一些常用組件的配置及使用_基礎應用
- 2024-03-25 使用HttpURLConnection發送POST請求并攜帶請求參數
- 2022-06-29 利用python實現你說我猜游戲的完整實例_python
- 2023-12-21 npm install 報錯(npm ERR! errno: -4048, npm ERR! c
- 2023-04-10 Python中mmap模塊處理大文本的操作方法_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支