Domanda

I am trying to override the locale to use Czech locale no matter what is set in the phone. However, although when I try to get the current locale, it returns czech, but for plurals, it acts like it still takes the real phone locale.

Here is my code:

<application
    android:name=".xxx"
    android:allowBackup="true"
    android:icon="@drawable/logo"
    android:label="@string/app_name"
    android:theme="@style/Theme.mystyle"
    android:configChanges="locale"
    >

In application:

String lang = settings.getString("cs", "");
locale = new Locale(lang);
        Locale.setDefault(locale);
        config.locale = locale;
        getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
È stato utile?

Soluzione 2

In the end I found the correct solution. Gray Wolf's solution did not work for me for some reason. Maybe it is all about the API level you develop your app for.

This is the working code. Besides that, it is also necessary to add configChanges:locale to AndroidManifest. This should work on Android 4.0.1 and above.

public class MyApplication extends Application
{
private Locale locale = null;

@Override
public void onConfigurationChanged(Configuration newConfig)
{
    super.onConfigurationChanged(newConfig);
    if (locale != null)
    {
        newConfig.locale = locale;
        Locale.setDefault(locale);
        getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());
    }
}

@Override
public void onCreate()
{
    super.onCreate();
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    Configuration config = getBaseContext().getResources().getConfiguration();

    String lang = "cs";
    if (!"".equals(lang) && !config.locale.getLanguage().equals(lang))
    {
        locale = new Locale(lang);
        Locale.setDefault(locale);
        config.locale = locale;
        getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
    }
}
}

Altri suggerimenti

I posted on GitHub simple LocaleAssistant class I just tested with plurals for Slovak and also Czech language, and it worked on the device with default locale set to EN. Just call those two methods from within your custom Application on the member instance of LocaleAssistant.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top