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

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

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

快速定位與修復

修改記錄修改時間
新建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,發(fā)現之前的多語言切換失效了。經過一點點排除方式排查,發(fā)現是由于升到 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出來的,那繼續(xù)往下看
  }
  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;
  //......
  //這里可以看到,如果兩個配置相等,則直接跳過了,并沒有給新創(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,上面注釋已經非常清晰了。這里簡單總結下:

AppCompatActivity# attachBaseContext() 方法在 Androidx 進行了包裝,具體實現在 AppCompatDelegateImpl# attachBaseContext2() 。

該包裝方法實現了兩套邏輯:

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

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

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

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

相關文章

最新評論