Activity is blinking after locale change in Android 4.1+

偶尔善良 提交于 2019-12-19 03:37:31

问题


I have implemented custom locale selection about a year ago but after 4.1 release users start to complain on constant activity blinking. Here is code I'm using (compiled from different SO answers):

public final class TestApplication extends Application
{
    private Locale desiredLocale = new Locale("ru-RU");

    @Override
    public void onCreate() {
        super.onCreate();
        updateLocale(new Configuration());
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
        updateLocale(newConfig);
    }

    private void updateLocale(Configuration newConfig) {
        newConfig.locale = desiredLocale;
        Locale.setDefault(desiredLocale);
        getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());        
    }    
}

Application contains only one empty activity, which is recreated by Android every second after I change device orientation. Here is the source of sample.

It looks like all applications which use this technique became invalid. What is the correct approach?


回答1:


This line caused solution to fail:

getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());

Correct (at least it works) implementation is defined here https://stackoverflow.com/a/14010044/554336 :

Configuration config = new Configuration();
config.locale = locale;
getResources().updateConfiguration(config, getResources().getDisplayMetrics());

So new configuration instance should be created every time.



来源:https://stackoverflow.com/questions/15406345/activity-is-blinking-after-locale-change-in-android-4-1

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