【问题标题】:Android: Debug and Release different languageAndroid:调试和发布不同的语言
【发布时间】:2021-07-29 17:15:25
【问题描述】:
现在,我正在使用 Kotlin 构建一个 Android 应用。这个应用程序支持多种语言,我将字符串放入 strings.xml。我已经使用 Locale 开发了应用程序来更改语言。
这是我的资源树:
res
-values
--strings.xml
-values-ko-rKR
--strings.xml
我希望我的调试应用程序使用英文版,而我的发布应用程序使用韩文版。有没有办法在构建设置上做到这一点?如果我不能这样做,我可以在哪里轻松设置我的默认语言环境?
【问题讨论】:
标签:
android
locale
build-settings
【解决方案1】:
要设置设备设置中设置的其他语言环境,只需添加调试/发布检查:
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 并让您的应用的所有 Activity 都继承自它
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"