欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

多語言切換在Androidx失效的踩坑解決記錄

 更新時(shí)間:2023年01月12日 10:03:47   作者:青杉  
這篇文章主要為大家介紹了多語言切換在Androidx失效的踩坑解決記錄詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

快速定位與修復(fù)

修改記錄修改時(shí)間
新建2021.01.09

出現(xiàn)問題時(shí)的調(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,但就是因?yàn)樗o包的這一層邏輯有問題,導(dǎo)致了多語言切換時(shí)效。所以咱們手動(dòng)給包一層

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)多語言切換的實(shí)現(xiàn)。所以我封裝了一個(gè)庫(實(shí)質(zhì)就是一個(gè)工具類),該庫已經(jīng)適配了該問題,大家可以直接copy出來使用

Github : github.com/StefanShan/…

詳細(xì)排查過程與原理

最近項(xiàng)目升級為 Androidx,發(fā)現(xiàn)之前的多語言切換失效了。經(jīng)過一點(diǎn)點(diǎn)排除方式排查,發(fā)現(xiàn)是由于升到 Androidx 后項(xiàng)目引入了 androidx.appcompat:appcompat:1.2.0來替代之前的v7包。那么根據(jù)多語言切換原理來看看是什么原因。

多語言切換原理:修改 context 的 Locale 配置,將新生成的 context 設(shè)置給 attachBaseContext 實(shí)現(xiàn)配置的替換。

先來看下 androidx 下的 AppCompatActivity# attachBaseContext() 源碼

@Override
protected void attachBaseContext(Context newBase) {
  super.attachBaseContext(getDelegate().attachBaseContext2(newBase));
}

哦~ 有個(gè)代理類處理了傳入的 context,看下這個(gè)代理類 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 類的實(shí)現(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)行對比,覆蓋修改過的配置。
  * 這里有個(gè)關(guān)鍵因素,通過 packageManager 獲取的配置與 context 的配置進(jìn)行 diff 更新,并將 diff 結(jié)果賦值給新建的 configration。這就會導(dǎo)致,當(dāng)這一次切換成功后,殺死進(jìn)程下次啟動(dòng)時(shí),由于 packageManager 配置的語言 與 context 配置的語言一致,而直接跳過,并沒有給新建的 configration進(jìn)行賦值。最終導(dǎo)致多語言切換失效。同理,從 ActivityA 設(shè)置了多語言,然后重啟 ActivityA,再從ActivityA 跳轉(zhuǎn)到 ActivityB,此時(shí)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;
  //......
  //這里可以看到,如果兩個(gè)配置相等,則直接跳過了,并沒有給新創(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)行了包裝,具體實(shí)現(xiàn)在 AppCompatDelegateImpl# attachBaseContext2() 。

該包裝方法實(shí)現(xiàn)了兩套邏輯:

傳入的 context 是經(jīng)過 ContextThemeWrapper 封裝的,則直接使用該 context 配置(包含語言)進(jìn)行覆蓋

傳入的 context 未經(jīng)過 ContextThemeWrapper 封裝,則從 PackageManger 中獲取配置(包含語言),然后和傳入的 context 配置(包含語言)進(jìn)行對比,并新創(chuàng)建了一個(gè) configration 對象,如果兩者有對比不同的配置則賦值給這個(gè) configration,如果相同則跳過,最后將這個(gè)新建的 configration 作為最終配置結(jié)果進(jìn)行覆蓋。

而多語言問題就出現(xiàn)在 [2] 這套邏輯上,如果 PackageManager 與 傳入的 context 某個(gè)配置項(xiàng)一致時(shí)就不會給新建的 configration 賦值該配置項(xiàng)。這就會導(dǎo)致當(dāng)這一次切換成功后,殺死進(jìn)程下次啟動(dòng)時(shí),由于 packageManager 配置的語言 與 context 配置的語言一致,而直接跳過,并沒有給新建的 configration進(jìn)行賦值,最終表現(xiàn)就是多語言失效。

以上就是多語言切換在Androidx失效的踩坑解決記錄的詳細(xì)內(nèi)容,更多關(guān)于多語言切換Androidx失效的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論