问题描述
现在,我正在使用 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"