Android 切换系统语言

2021-01-24  本文已影响0人  一个不安分的Android开发

切换系统语言分为下面两个步骤:

1. 创建不同语言资源;
2. 替换当前页面 Context 所持有的资源;

一、创建不同语言资源

创建步骤如下:

创建资源1.png 创建资源2.png 创建资源3.png 创建资源4.png

二、替换资源

  //可以在 BaseActivity 中使用
  @Override
  protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(Utils.attachBaseContext(newBase));
  }

  public static Context attachBaseContext(Context context) {
    //不同版本设置方式不一样
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
      return createResources(context);
    } else {
      updateResources(context);
      return context;
    }
  }

  @TargetApi(Build.VERSION_CODES.N)
  private static Context createResources(Context context) {
    Resources resources = context.getResources();
    DisplayMetrics dm = resources.getDisplayMetrics();
    Configuration configuration = resources.getConfiguration();
    //获取语言设置,一般用户设置的语言优先级更高,如果用户没有设置,则获取系统语言
    Locale targetLocale = getLocale(context);
    configuration.setLocale(targetLocale);
    resources.updateConfiguration(configuration, dm);
    //创建配置
    return context.createConfigurationContext(configuration);
  }

  public static void updateResources(Context pContext) {
    Locale targetLocale = getLocale(pContext);
    Configuration configuration = pContext.getResources().getConfiguration();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
      configuration.setLocale(targetLocale);
    } else {
      configuration.locale = targetLocale;
    }
    Resources resources = pContext.getResources();
    DisplayMetrics dm = resources.getDisplayMetrics();
    //更新配置
    resources.updateConfiguration(configuration, dm);
  }

  public static Locale getSystemLocale(Context context) {
    Locale locale;
    //7.0有多语言设置获取顶部的语言
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
      locale = LocaleList.getDefault().get(0);
    } else {
      locale = context.getResources().getConfiguration().locale;
    }
    return locale;
  }

注意:
不能使用 Application 的 Context 来获取文字资源,必须使用 Activity 的 Context;

上一篇 下一篇

猜你喜欢

热点阅读