Android 切换系统语言

本文详细介绍了在Android应用中如何实现系统语言切换的两个关键步骤:创建不同语言资源和替换当前页面的Context资源。通过在BaseActivity中覆盖attachBaseContext()方法,并调用Utils的attachBaseContext()静态方法,结合Build.VERSION.SDK_INT判断使用不同的API进行资源更新。同时,注意不能使用Application的Context获取资源,必须使用Activity的Context。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

1. 创建不同语言资源;

2. 替换当前页面 Context 所持有的资源;

一、创建不同语言资源

创建步骤如下:

二、替换资源

  • 界面需要重新创建,使用 recreate(); 或者 重新打开界面。
  • 在 attachBaseContext(Context) 方法中替换Context的资源。
  //可以在 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;

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值