多語言切換在Androidx失效的踩坑解決記錄
快速定位與修復(fù)
修改記錄 | 修改時間 |
---|---|
新建 | 2021.01.09 |
出現(xiàn)問題時的調(diào)用方式:
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
,但就是因為他給包的這一層邏輯有問題,導(dǎo)致了多語言切換時效。所以咱們手動給包一層
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); } }
封裝
上面僅說明了怎么解決問題,沒有體現(xiàn)多語言切換的實現(xiàn)。所以我封裝了一個庫(實質(zhì)就是一個工具類),該庫已經(jīng)適配了該問題,大家可以直接copy出來使用
Github : github.com/StefanShan/…
詳細(xì)排查過程與原理
最近項目升級為 Androidx,發(fā)現(xiàn)之前的多語言切換失效了。經(jīng)過一點(diǎn)點(diǎn)排除方式排查,發(fā)現(xiàn)是由于升到 Androidx 后項目引入了 androidx.appcompat:appcompat:1.2.0
來替代之前的v7
包。那么根據(jù)多語言切換原理來看看是什么原因。
多語言切換原理:修改 context 的 Locale 配置,將新生成的 context 設(shè)置給 attachBaseContext 實現(xiàn)配置的替換。
先來看下 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出來的,那繼續(xù)往下看 } return mDelegate; }
// 這里直接看 AppCompatDelegateImpl 類,該類是 AppCompatDelegate 類的實現(xiàn)類 @NonNull @Override @CallSuper public Context attachBaseContext2(@NonNull final Context baseContext) { //...... /** * 這段邏輯是:如果傳入的 context 是經(jīng)過 ContextThemeWrapper 封裝的,則直接使用該 context 配置進(jìn)行覆蓋 */ // 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 配置進(jìn)行對比,覆蓋修改過的配置。 * 這里有個關(guān)鍵因素,通過 packageManager 獲取的配置與 context 的配置進(jìn)行 diff 更新,并將 diff 結(jié)果賦值給新建的 configration。這就會導(dǎo)致,當(dāng)這一次切換成功后,殺死進(jìn)程下次啟動時,由于 packageManager 配置的語言 與 context 配置的語言一致,而直接跳過,并沒有給新建的 configration進(jìn)行賦值。最終導(dǎo)致多語言切換失效。同理,從 ActivityA 設(shè)置了多語言,然后重啟 ActivityA,再從ActivityA 跳轉(zhuǎn)到 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); //這里是關(guān)鍵 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; //...... //這里可以看到,如果兩個配置相等,則直接跳過了,并沒有給新創(chuàng)建的 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,上面注釋已經(jīng)非常清晰了。這里簡單總結(jié)下:
AppCompatActivity# attachBaseContext()
方法在 Androidx 進(jìn)行了包裝,具體實現(xiàn)在 AppCompatDelegateImpl# attachBaseContext2()
。
該包裝方法實現(xiàn)了兩套邏輯:
傳入的 context 是經(jīng)過 ContextThemeWrapper 封裝的,則直接使用該 context 配置(包含語言)進(jìn)行覆蓋
傳入的 context 未經(jīng)過 ContextThemeWrapper 封裝,則從 PackageManger 中獲取配置(包含語言),然后和傳入的 context 配置(包含語言)進(jìn)行對比,并新創(chuàng)建了一個 configration 對象,如果兩者有對比不同的配置則賦值給這個 configration,如果相同則跳過,最后將這個新建的 configration 作為最終配置結(jié)果進(jìn)行覆蓋。
而多語言問題就出現(xiàn)在 [2] 這套邏輯上,如果 PackageManager 與 傳入的 context 某個配置項一致時就不會給新建的 configration 賦值該配置項。這就會導(dǎo)致當(dāng)這一次切換成功后,殺死進(jìn)程下次啟動時,由于 packageManager 配置的語言 與 context 配置的語言一致,而直接跳過,并沒有給新建的 configration進(jìn)行賦值,最終表現(xiàn)就是多語言失效。
以上就是多語言切換在Androidx失效的踩坑解決記錄的詳細(xì)內(nèi)容,更多關(guān)于多語言切換Androidx失效的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Android開發(fā)中記一個SwipeMenuListView側(cè)滑刪除錯亂的Bug
這篇文章主要介紹了Android開發(fā)中記一個SwipeMenuListView側(cè)滑刪除錯亂的Bug的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-09-09Android開發(fā)之機(jī)頂盒上gridview和ScrollView的使用詳解
這篇文章主要介紹了Android開發(fā)之機(jī)頂盒上gridview和ScrollView的使用詳解的相關(guān)資料,需要的朋友可以參考下2016-02-02Android編程UI設(shè)計之GridView和ImageView的用法
這篇文章主要介紹了Android編程UI設(shè)計之GridView和ImageView的用法,結(jié)合實例形式較為詳細(xì)的分析了Android中GridView和ImageView組件的相關(guān)方法使用技巧,需要的朋友可以參考下2016-01-01Android上傳多張圖片的實例代碼(RxJava異步分發(fā))
本篇文章主要介紹了Android上傳多張圖片的實例代碼(RxJava異步分發(fā)),具有一定的參考價值,有興趣的可以了解一下2017-08-08android仿Adapter實現(xiàn)自定義PagerAdapter方法示例
這篇文章主要給大家介紹了關(guān)于android仿Adapter實現(xiàn)自定義PagerAdapter的相關(guān)資料,文中詳細(xì)介紹了關(guān)于PagerAdapter的用法,對大家的理解和學(xué)習(xí)具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-11-11