Activity is blinking after locale change in Androi

2020-03-04 02:36发布

问题:

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.