android - Android:调试和发布不同的语言
问题描述
现在,我正在使用 Kotlin 构建一个 Android 应用程序。这个应用程序支持多种语言,我将字符串放入 strings.xml。我已经使用 Locale 开发了应用程序来更改语言。
这是我的资源树:
res
-values
--strings.xml
-values-ko-rKR
--strings.xml
我希望我的调试应用程序使用英文版,而我的发布应用程序使用韩文版。有没有办法在构建设置上做到这一点?如果我不能这样做,我可以在哪里轻松设置我的默认语言环境?
解决方案
要设置设备设置中设置的其他语言环境,只需添加调试/发布检查:
public class LocaleUtil {
public static Context setForceLocale(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResources(context);
} else {
return lockLocale(context);
}
}
public static Context lockLocale(Context context) {
Locale myLocale = new Locale("en-US");
Locale.setDefault(myLocale);
Resources res = context.getResources();
Configuration conf = res.getConfiguration();
conf.setLocale(myLocale);
return context.createConfigurationContext(conf);
}
private static Context updateResources(Context context) {
Locale locale = new Locale("en-US");
Locale.setDefault(locale);
Resources res = context.getResources();
Configuration config = new Configuration(res.getConfiguration());
config.setLocale(locale);
return context.createConfigurationContext(config);
}
}
在您的应用程序类中:
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleUtil.setForceLocale(base));
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
LocaleUtil.setForceLocale(this);
}
添加一个 ParentActivity 并使您的应用程序的所有活动都继承自这个活动
public abstract class ParentActivity extends AppCompatActivity {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleUtil.setForceLocale(base));
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
LocaleUtil.setForceLocale(this);
}
}
}
最后将这一行添加到所有活动标签内的 AndroidManifest 中:
android:configChanges="keyboardHidden|orientation|screenSize"
推荐阅读
- excel - 使用特定语句比较 excel 列
- html - MDL 浮动标签文本字段:更改其颜色
- html - 隐藏元素未正确定位
- flutter - 错误:flutter_quill-2.0.6 中没有名为“supportedDevices”的命名参数
- php - CSS - Adding multiple WooCommerce Local fonts
- flutter - How to add score card in a video using flutter
- python - How to set locale for csv.reader in Python?
- python - 在一列内计算并基于另一列进行平均
- python-3.x - 如何对不同长度的 Python Pandas groupby 对象进行切片?
- mysql - Django 中的 save() 函数会覆盖数据库表中的旧数据吗?