首页 > 解决方案 > Android:调试和发布不同的语言

问题描述

现在,我正在使用 Kotlin 构建一个 Android 应用程序。这个应用程序支持多种语言,我将字符串放入 strings.xml。我已经使用 Locale 开发了应用程序来更改语言。

这是我的资源树:

res
-values
--strings.xml
-values-ko-rKR
--strings.xml

我希望我的调试应用程序使用英文版,而我的发布应用程序使用韩文版。有没有办法在构建设置上做到这一点?如果我不能这样做,我可以在哪里轻松设置我的默认语言环境?

标签: androidlocalebuild-settings

解决方案


要设置设备设置中设置的其他语言环境,只需添加调试/发布检查:

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"

推荐阅读