Change language programatically in Android with country

徘徊边缘 提交于 2019-12-11 18:25:04

问题


I try to change my locale in an android application. If I use only language all is ok, but today I added portuguese-br translation to my app.

Code:

Locale locale;
        if(language.contains("-"))  // In this case, the locale specify also the country
        {
            String[] country_locale = language.split("-");
            locale = new Locale(country_locale[0], country_locale[1]); 
        }
        else
            locale = new Locale(language); 
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        getApplicationContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());

All is ok untill last line. I know because in a previous piece of my program i could get some string with the correct pt-br locale with this code:

Resources resources = new Resources(ctx.getAssets(), ctx.getResources().getDisplayMetrics(), new_config);

updateConfiguration set my locale to English if Locale was defined with a country code.

String.xml is in values-pt-rBR

While debugging Locale value is set to pt-BR.

EDIT: After further tests, this works on my Android phone, but doesn't work on my tablet (both Sambung with android 4.4.2). What could be the reason?

EDIT 2: Also over the emulator work if I use a phone, not work if I use a tablet.


回答1:


On your current Activity, try call the follow after your code:

finish();
startActivity(getIntent());

This will recreate your Activity and, then, reload the string resources.



来源:https://stackoverflow.com/questions/28886896/change-language-programatically-in-android-with-country

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!