Android应用杀死重启后如何加载已切换的语言并保持设置
解决Android应用语言切换后重启恢复默认的问题
看起来你已经搞定了语言切换的即时生效逻辑,但问题出在应用重启时没有加载之前保存的语言设置——这就是为什么杀死应用再打开会回到默认英文的原因。下面我给你一套完整的持久化方案,确保语言设置在应用重启后依然保留:
核心思路
我们需要在应用启动的最早阶段(比如每个Activity初始化前)读取存在SharedPreferences里的语言代码,重新设置应用的Locale配置。推荐用BaseActivity的方式,因为它能确保所有页面都能正确应用语言设置,避免个别页面遗漏。
步骤1:创建BaseActivity统一处理语言加载
创建一个所有Activity都继承的基类,在attachBaseContext方法中加载保存的语言——这个方法在Activity创建的最早期调用,能保证语言设置在页面渲染前生效:
public class BaseActivity extends AppCompatActivity { @Override protected void attachBaseContext(Context newBase) { // 从SharedPreferences读取保存的语言代码,默认英文 SharedPreferences prefs = newBase.getSharedPreferences("Settings", MODE_PRIVATE); String savedLocaleCode = prefs.getString("My_Lang", "en"); // 更新Context的Locale配置 Context updatedContext = updateLocaleContext(newBase, savedLocaleCode); super.attachBaseContext(updatedContext); } private Context updateLocaleContext(Context context, String localeCode) { Locale targetLocale = new Locale(localeCode.toLowerCase()); Locale.setDefault(targetLocale); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // Android 7.0及以上使用官方推荐的createConfigurationContext return updateLocaleForN(context, targetLocale); } else { // 低版本使用传统方式适配 return updateLocaleForLegacy(context, targetLocale); } } @TargetApi(Build.VERSION_CODES.N) private Context updateLocaleForN(Context context, Locale locale) { Configuration config = context.getResources().getConfiguration(); config.setLocale(locale); config.setLayoutDirection(locale); return context.createConfigurationContext(config); } @SuppressWarnings("deprecation") private Context updateLocaleForLegacy(Context context, Locale locale) { Resources resources = context.getResources(); Configuration config = resources.getConfiguration(); config.locale = locale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { config.setLayoutDirection(locale); } resources.updateConfiguration(config, resources.getDisplayMetrics()); return context; } }
步骤2:让所有Activity继承BaseActivity
比如你的StartupActivity和其他页面都改成继承BaseActivity,确保全局语言设置一致:
public class StartupActivity extends BaseActivity { // 你的Activity原有逻辑... }
步骤3:保留你原来的语言切换逻辑
你之前写的切换代码是没问题的,继续保留就行——它负责切换语言并将设置保存到SharedPreferences:
// 你原来的语言切换代码,无需修改 Resources res = getResources(); DisplayMetrics dm = res.getDisplayMetrics(); Configuration conf = res.getConfiguration(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { conf.setLocale(new Locale(localeCode.toLowerCase())); } else { conf.locale = new Locale(localeCode.toLowerCase()); } res.updateConfiguration(conf, dm); SharedPreferences.Editor editor = getSharedPreferences("Settings", MODE_PRIVATE).edit(); editor.putString("My_Lang", localeCode); editor.apply(); Intent refresh = new Intent(this, StartupActivity.class); startActivity(refresh); finish();
现在你可以测试一下:切换语言后杀死应用,重新打开应该就能看到上次设置的语言了。
内容的提问来源于stack exchange,提问作者Vikas Acharya
相关产品推荐
相关产品推荐

