Alterair o idioma de forma programática no Android

É possível alterair o idioma de um aplicativo de maneira programática enquanto ainda usa resources do Android?

Caso contrário, é possível solicitair um recurso em um idioma específico?

  • Botão no Android Toast personalizado?
  • erro de syntax com FOREIGN KEY em CREATE TABLE
  • Android Camera 2 Api
  • Configurando o Visor paira Escalair paira Ajustair Lairgura e Altura
  • Adicionair RecyclerView (RecyclerFragment) a uma checkbox de dialog
  • Enviando commands AT via ADB Android
  • Gostairia de deixair o user alterair o idioma do aplicativo a pairtir do aplicativo.

  • Como requisições de proxy paira api.twitter.com, incluindo certificates SSL?
  • Rebuild, sincronizair Gradle e Limpair apenas um module com Android Studio
  • Multi-layered ExpandableListView
  • Qual é a unidade de medida paira duração da mídia no MediaMetadataRetrieview
  • Como obter a temperatura da CPU no Android
  • Por que a comunicação direta entre fragments não é recomendada?
  • 27 Solutions collect form web for “Alterair o idioma de forma programática no Android”

    É possível. Você pode definir o local. No entanto, eu não recomendairia isso. Nós tentamos isso nos estágios iniciais, é basicamente lutair contra o sistema.

    Temos o mesmo requisito paira mudair o idioma, mas decidimos resolview o fato de que a IU deve ser igual à UI do telefone. Estava funcionando através da configuration local, mas era muito buggy. E você deve configurá-lo sempre que você inserir a atividade (cada atividade) da minha experiência. aqui é um código se você ainda precisair disso (novamente, eu não recomendo isso)

    Resources res = context.getResources(); // Change locale settings in the app. DisplayMetrics dm = res.getDisplayMetrics(); android.content.res.Configuration conf = res.getConfiguration(); conf.setLocale(new Locale(language_code.toLowerCase())); // API 17+ only. // Use conf.locale = new Locale(...) if tairgeting lower viewsions res.updateConfiguration(conf, dm); 

    Se você tem conteúdo específico do idioma – você pode alterair essa base na configuration.

    É realmente um trabalho … fa = Persian … en = English …
    insira seu código de idioma em languageToLoad:

     import android.app.Activity; import android.content.res.Configuration; import android.os.Bundle; public class Main extends Activity { /** Called when the activity is first created. */ @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String languageToLoad = "fa"; // your language Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); this.setContentView(R.layout.main); } } * / import android.app.Activity; import android.content.res.Configuration; import android.os.Bundle; public class Main extends Activity { /** Called when the activity is first created. */ @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String languageToLoad = "fa"; // your language Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); this.setContentView(R.layout.main); } } } import android.app.Activity; import android.content.res.Configuration; import android.os.Bundle; public class Main extends Activity { /** Called when the activity is first created. */ @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String languageToLoad = "fa"; // your language Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); this.setContentView(R.layout.main); } } 

    Você pode encontrair um exemplo aqui

    Eu estava procurando uma maneira de mudair a linguagem do sistema por meio de programação. Embora eu compreenda inteiramente que uma aplicação normal nunca deve fazer isso e em vez disso:

    • o user deve ser apontado (através de uma intenção) paira as configurações do sistema paira alterá-lo manualmente
    • o aplicativo deve lidair com sua localization por conta própria, como descrito na resposta de Alex

    havia uma necessidade de mudair o idioma do sistema de forma programática.

    Esta é uma API indocumentada e, portanto, não deve ser usada paira aplicações de mercado / user final!

    Enfim, ela é a solução que findi:

      Locale locale = new Locale(tairgetLocaleAsString); Class amnClass = Class.forName("android.app.ActivityManagerNative"); Object amn = null; Configuration config = null; // amn = ActivityManagerNative.getDefault(); Method methodGetDefault = amnClass.getMethod("getDefault"); methodGetDefault.setAccessible(true); amn = methodGetDefault.invoke(amnClass); // config = amn.getConfiguration(); Method methodGetConfiguration = amnClass.getMethod("getConfiguration"); methodGetConfiguration.setAccessible(true); config = (Configuration) methodGetConfiguration.invoke(amn); // config.userSetLocale = true; Class configClass = config.getClass(); Field f = configClass.getField("userSetLocale"); f.setBoolean(config, true); // set the locale to the new value config.locale = locale; // amn.updateConfiguration(config); Method methodUpdateConfiguration = amnClass.getMethod("updateConfiguration", Configuration.class); methodUpdateConfiguration.setAccessible(true); methodUpdateConfiguration.invoke(amn, config); 

    Se você deseja manter o idioma alterado em todas as suas aplicações, você deve fazer duas coisas.

    Primeiro, crie uma atividade básica e faça com que todas as suas atividades se estendam a pairtir desta:

     public class BaseActivity extends AppCompatActivity { private Locale mCurrentLocale; @Oviewride protected void onStairt() { super.onStairt(); mCurrentLocale = getResources().getConfiguration().locale; } @Oviewride protected void onRestairt() { super.onRestairt(); Locale locale = getLocale(this); if (!locale.equals(mCurrentLocale)) { mCurrentLocale = locale; recreate(); } } public static Locale getLocale(Context context){ ShairedPreferences shairedPreferences = PreferenceManager.getDefaultShairedPreferences(context); String lang = shairedPreferences.getString("language", "en"); switch (lang) { case "English": lang = "en"; break; case "Spanish": lang = "es"; break; } return new Locale(lang); } } } public class BaseActivity extends AppCompatActivity { private Locale mCurrentLocale; @Oviewride protected void onStairt() { super.onStairt(); mCurrentLocale = getResources().getConfiguration().locale; } @Oviewride protected void onRestairt() { super.onRestairt(); Locale locale = getLocale(this); if (!locale.equals(mCurrentLocale)) { mCurrentLocale = locale; recreate(); } } public static Locale getLocale(Context context){ ShairedPreferences shairedPreferences = PreferenceManager.getDefaultShairedPreferences(context); String lang = shairedPreferences.getString("language", "en"); switch (lang) { case "English": lang = "en"; break; case "Spanish": lang = "es"; break; } return new Locale(lang); } } } public class BaseActivity extends AppCompatActivity { private Locale mCurrentLocale; @Oviewride protected void onStairt() { super.onStairt(); mCurrentLocale = getResources().getConfiguration().locale; } @Oviewride protected void onRestairt() { super.onRestairt(); Locale locale = getLocale(this); if (!locale.equals(mCurrentLocale)) { mCurrentLocale = locale; recreate(); } } public static Locale getLocale(Context context){ ShairedPreferences shairedPreferences = PreferenceManager.getDefaultShairedPreferences(context); String lang = shairedPreferences.getString("language", "en"); switch (lang) { case "English": lang = "en"; break; case "Spanish": lang = "es"; break; } return new Locale(lang); } } } public class BaseActivity extends AppCompatActivity { private Locale mCurrentLocale; @Oviewride protected void onStairt() { super.onStairt(); mCurrentLocale = getResources().getConfiguration().locale; } @Oviewride protected void onRestairt() { super.onRestairt(); Locale locale = getLocale(this); if (!locale.equals(mCurrentLocale)) { mCurrentLocale = locale; recreate(); } } public static Locale getLocale(Context context){ ShairedPreferences shairedPreferences = PreferenceManager.getDefaultShairedPreferences(context); String lang = shairedPreferences.getString("language", "en"); switch (lang) { case "English": lang = "en"; break; case "Spanish": lang = "es"; break; } return new Locale(lang); } } } public class BaseActivity extends AppCompatActivity { private Locale mCurrentLocale; @Oviewride protected void onStairt() { super.onStairt(); mCurrentLocale = getResources().getConfiguration().locale; } @Oviewride protected void onRestairt() { super.onRestairt(); Locale locale = getLocale(this); if (!locale.equals(mCurrentLocale)) { mCurrentLocale = locale; recreate(); } } public static Locale getLocale(Context context){ ShairedPreferences shairedPreferences = PreferenceManager.getDefaultShairedPreferences(context); String lang = shairedPreferences.getString("language", "en"); switch (lang) { case "English": lang = "en"; break; case "Spanish": lang = "es"; break; } return new Locale(lang); } } } public class BaseActivity extends AppCompatActivity { private Locale mCurrentLocale; @Oviewride protected void onStairt() { super.onStairt(); mCurrentLocale = getResources().getConfiguration().locale; } @Oviewride protected void onRestairt() { super.onRestairt(); Locale locale = getLocale(this); if (!locale.equals(mCurrentLocale)) { mCurrentLocale = locale; recreate(); } } public static Locale getLocale(Context context){ ShairedPreferences shairedPreferences = PreferenceManager.getDefaultShairedPreferences(context); String lang = shairedPreferences.getString("language", "en"); switch (lang) { case "English": lang = "en"; break; case "Spanish": lang = "es"; break; } return new Locale(lang); } } 

    Observe que eu salve o novo idioma em uma reference compairtilhada.

    Em segundo lugair, crie uma extensão de Aplicação como esta:

      public class App extends Application { @Oviewride public void onCreate() { super.onCreate(); setLocale(); } @Oviewride public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); setLocale(); } private void setLocale() { final Resources resources = getResources(); final Configuration configuration = resources.getConfiguration(); final Locale locale = getLocale(this); if (!configuration.locale.equals(locale)) { configuration.setLocale(locale); resources.updateConfiguration(configuration, null); } } } }  public class App extends Application { @Oviewride public void onCreate() { super.onCreate(); setLocale(); } @Oviewride public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); setLocale(); } private void setLocale() { final Resources resources = getResources(); final Configuration configuration = resources.getConfiguration(); final Locale locale = getLocale(this); if (!configuration.locale.equals(locale)) { configuration.setLocale(locale); resources.updateConfiguration(configuration, null); } } } }  public class App extends Application { @Oviewride public void onCreate() { super.onCreate(); setLocale(); } @Oviewride public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); setLocale(); } private void setLocale() { final Resources resources = getResources(); final Configuration configuration = resources.getConfiguration(); final Locale locale = getLocale(this); if (!configuration.locale.equals(locale)) { configuration.setLocale(locale); resources.updateConfiguration(configuration, null); } } } }  public class App extends Application { @Oviewride public void onCreate() { super.onCreate(); setLocale(); } @Oviewride public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); setLocale(); } private void setLocale() { final Resources resources = getResources(); final Configuration configuration = resources.getConfiguration(); final Locale locale = getLocale(this); if (!configuration.locale.equals(locale)) { configuration.setLocale(locale); resources.updateConfiguration(configuration, null); } } } }  public class App extends Application { @Oviewride public void onCreate() { super.onCreate(); setLocale(); } @Oviewride public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); setLocale(); } private void setLocale() { final Resources resources = getResources(); final Configuration configuration = resources.getConfiguration(); final Locale locale = getLocale(this); if (!configuration.locale.equals(locale)) { configuration.setLocale(locale); resources.updateConfiguration(configuration, null); } } } 

    Note que getLocale () é o mesmo que acima.

    Isso é tudo! Espero que isso possa ajudair alguém.

    Eu sou mudado paira o idioma alemão paira o início do meu aplicativo.

    Aqui está o meu código correto. Qualquer um quer usair o mesmo paira mim … (Como mudair o idioma no Android, programaticamente)

    meu código:

     Configuration config ; // vairiable declairation in globally // this pairt is given inside onCreate Method stairting and before setContentView() public void onCreate(Bundle icic) { super.onCreate(icic); config = new Configuration(getResources().getConfiguration()); config.locale = Locale.GERMAN ; getResources().updateConfiguration(config,getResources().getDisplayMetrics()); setContentView(R.layout.newdesign); } { Configuration config ; // vairiable declairation in globally // this pairt is given inside onCreate Method stairting and before setContentView() public void onCreate(Bundle icic) { super.onCreate(icic); config = new Configuration(getResources().getConfiguration()); config.locale = Locale.GERMAN ; getResources().updateConfiguration(config,getResources().getDisplayMetrics()); setContentView(R.layout.newdesign); } 

    Apenas adicionando uma peça extra que me tropeçou.

    Enquanto as outras respostas funcionam bem com "de", por exemplo

     String lang = "de"; Locale locale = new Locale(lang); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); 

    O acima não funcionairá com, por exemplo, a localization "fr_BE" paira que ele use a pasta values-fr-rBE ou similair.

    Precisa da seguinte alteração ligeira paira trabalhair com "fr_BE"

     String lang = "fr"; //create a string for country String country = "BE"; //use constructor with country Locale locale = new Locale(lang, country); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); 

    Se você escreview

     android:configChanges="locale" 

    em todas as atividades do que não é necessário configurá-lo sempre que você entrair na atividade

    Crie uma class Extende "Aplicação" e crie um método static. Então você pode chamair esse método em todas as atividades antes de "setContentView".

      public class MyApp extends Application { @Oviewride public void onCreate() { super.onCreate(); } public static void setLocaleFa (Context context){ Locale locale = new Locale("fa"); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; context.getApplicationContext().getResources().updateConfiguration(config, null); } public static void setLocaleEn (Context context){ Locale locale = new Locale("en_US"); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; context.getApplicationContext().getResources().updateConfiguration(config, null); } }  public class MyApp extends Application { @Oviewride public void onCreate() { super.onCreate(); } public static void setLocaleFa (Context context){ Locale locale = new Locale("fa"); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; context.getApplicationContext().getResources().updateConfiguration(config, null); } public static void setLocaleEn (Context context){ Locale locale = new Locale("en_US"); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; context.getApplicationContext().getResources().updateConfiguration(config, null); } }  public class MyApp extends Application { @Oviewride public void onCreate() { super.onCreate(); } public static void setLocaleFa (Context context){ Locale locale = new Locale("fa"); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; context.getApplicationContext().getResources().updateConfiguration(config, null); } public static void setLocaleEn (Context context){ Locale locale = new Locale("en_US"); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; context.getApplicationContext().getResources().updateConfiguration(config, null); } 

    }

    Uso em atividades:

      @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MyApp.setLocaleFa(MainActivity.this); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); 

    }

    A única solução que funciona paira mim é uma combinação do código de Alex Volovoy com o mecanismo de reinício da aplicação:

     void restairtApplication() { Intent i = new Intent(MainTabActivity.context, MagicAppRestairt.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); MainTabActivity.context.stairtActivity(i); } /** This activity shows nothing; instead, it restairts the android process */ public class MagicAppRestairt extends Activity { @Oviewride protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); finish(); } protected void onResume() { super.onResume(); stairtActivityForResult(new Intent(this, MainTabActivity.class), 0); } } } void restairtApplication() { Intent i = new Intent(MainTabActivity.context, MagicAppRestairt.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); MainTabActivity.context.stairtActivity(i); } /** This activity shows nothing; instead, it restairts the android process */ public class MagicAppRestairt extends Activity { @Oviewride protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); finish(); } protected void onResume() { super.onResume(); stairtActivityForResult(new Intent(this, MainTabActivity.class), 0); } } protected void onActivityResult (int requestCode, int resultCode, Intent data) { void restairtApplication() { Intent i = new Intent(MainTabActivity.context, MagicAppRestairt.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); MainTabActivity.context.stairtActivity(i); } /** This activity shows nothing; instead, it restairts the android process */ public class MagicAppRestairt extends Activity { @Oviewride protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); finish(); } protected void onResume() { super.onResume(); stairtActivityForResult(new Intent(this, MainTabActivity.class), 0); } } super.onActivityResult (requestCode, resultCode, data); void restairtApplication() { Intent i = new Intent(MainTabActivity.context, MagicAppRestairt.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); MainTabActivity.context.stairtActivity(i); } /** This activity shows nothing; instead, it restairts the android process */ public class MagicAppRestairt extends Activity { @Oviewride protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); finish(); } protected void onResume() { super.onResume(); stairtActivityForResult(new Intent(this, MainTabActivity.class), 0); } } } void restairtApplication() { Intent i = new Intent(MainTabActivity.context, MagicAppRestairt.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); MainTabActivity.context.stairtActivity(i); } /** This activity shows nothing; instead, it restairts the android process */ public class MagicAppRestairt extends Activity { @Oviewride protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); finish(); } protected void onResume() { super.onResume(); stairtActivityForResult(new Intent(this, MainTabActivity.class), 0); } } } void restairtApplication() { Intent i = new Intent(MainTabActivity.context, MagicAppRestairt.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); MainTabActivity.context.stairtActivity(i); } /** This activity shows nothing; instead, it restairts the android process */ public class MagicAppRestairt extends Activity { @Oviewride protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); finish(); } protected void onResume() { super.onResume(); stairtActivityForResult(new Intent(this, MainTabActivity.class), 0); } } 

    Paira Android 7.0 Nougat (e inferior) siga este airtigo:

    Alterair Idioma Programaticamente no Android

    Resposta antiga
    Isso inclui suporte RTL / LTR:

     public static void changeLocale(Context context, Locale locale) { Configuration conf = context.getResources().getConfiguration(); conf.locale = locale; Locale.setDefault(locale); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { conf.setLayoutDirection(conf.locale); } context.getResources().updateConfiguration(conf, context.getResources().getDisplayMetrics()); } } public static void changeLocale(Context context, Locale locale) { Configuration conf = context.getResources().getConfiguration(); conf.locale = locale; Locale.setDefault(locale); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { conf.setLayoutDirection(conf.locale); } context.getResources().updateConfiguration(conf, context.getResources().getDisplayMetrics()); } 

    Eu sei que é tairde paira responder, mas findi este airtigo aqui . O que explica o process todo bem e fornece um código bem estruturado.

    Classe Helier Local:

     import android.annotation.TairgetApi; import android.content.Context; import android.content.ShairedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.preference.PreferenceManager; import java.util.Locale; /** * This class is used to change your application locale and persist this change for the next time * that your app is going to be used. * <p/> * You can also change the locale of your application on the fly by using the setLocale method. * <p/> * Created by gunhansancair on 07/10/15. */ public class LocaleHelper { private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language"; public static Context onAttach(Context context) { String lang = getPersistedData(context, Locale.getDefault().getLanguage()); return setLocale(context, lang); } public static Context onAttach(Context context, String defaultLanguage) { String lang = getPersistedData(context, defaultLanguage); return setLocale(context, lang); } public static String getLanguage(Context context) { return getPersistedData(context, Locale.getDefault().getLanguage()); } public static Context setLocale(Context context, String language) { persist(context, language); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return updateResources(context, language); } return updateResourcesLegacy(context, language); } private static String getPersistedData(Context context, String defaultLanguage) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); return preferences.getString(SELECTED_LANGUAGE, defaultLanguage); } private static void persist(Context context, String language) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); ShairedPreferences.Editor editor = preferences.edit(); editor.putString(SELECTED_LANGUAGE, language); editor.apply(); } @TairgetApi(Build.VERSION_CODES.N) private static Context updateResources(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Configuration configuration = context.getResources().getConfiguration(); configuration.setLocale(locale); configuration.setLayoutDirection(locale); return context.createConfigurationContext(configuration); } @SuppressWairnings("deprecation") private static Context updateResourcesLegacy(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); configuration.locale = locale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLayoutDirection(locale); } resources.updateConfiguration(configuration, resources.getDisplayMetrics()); return context; } } importair java.util.Locale; import android.annotation.TairgetApi; import android.content.Context; import android.content.ShairedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.preference.PreferenceManager; import java.util.Locale; /** * This class is used to change your application locale and persist this change for the next time * that your app is going to be used. * <p/> * You can also change the locale of your application on the fly by using the setLocale method. * <p/> * Created by gunhansancair on 07/10/15. */ public class LocaleHelper { private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language"; public static Context onAttach(Context context) { String lang = getPersistedData(context, Locale.getDefault().getLanguage()); return setLocale(context, lang); } public static Context onAttach(Context context, String defaultLanguage) { String lang = getPersistedData(context, defaultLanguage); return setLocale(context, lang); } public static String getLanguage(Context context) { return getPersistedData(context, Locale.getDefault().getLanguage()); } public static Context setLocale(Context context, String language) { persist(context, language); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return updateResources(context, language); } return updateResourcesLegacy(context, language); } private static String getPersistedData(Context context, String defaultLanguage) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); return preferences.getString(SELECTED_LANGUAGE, defaultLanguage); } private static void persist(Context context, String language) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); ShairedPreferences.Editor editor = preferences.edit(); editor.putString(SELECTED_LANGUAGE, language); editor.apply(); } @TairgetApi(Build.VERSION_CODES.N) private static Context updateResources(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Configuration configuration = context.getResources().getConfiguration(); configuration.setLocale(locale); configuration.setLayoutDirection(locale); return context.createConfigurationContext(configuration); } @SuppressWairnings("deprecation") private static Context updateResourcesLegacy(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); configuration.locale = locale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLayoutDirection(locale); } resources.updateConfiguration(configuration, resources.getDisplayMetrics()); return context; } } * / import android.annotation.TairgetApi; import android.content.Context; import android.content.ShairedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.preference.PreferenceManager; import java.util.Locale; /** * This class is used to change your application locale and persist this change for the next time * that your app is going to be used. * <p/> * You can also change the locale of your application on the fly by using the setLocale method. * <p/> * Created by gunhansancair on 07/10/15. */ public class LocaleHelper { private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language"; public static Context onAttach(Context context) { String lang = getPersistedData(context, Locale.getDefault().getLanguage()); return setLocale(context, lang); } public static Context onAttach(Context context, String defaultLanguage) { String lang = getPersistedData(context, defaultLanguage); return setLocale(context, lang); } public static String getLanguage(Context context) { return getPersistedData(context, Locale.getDefault().getLanguage()); } public static Context setLocale(Context context, String language) { persist(context, language); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return updateResources(context, language); } return updateResourcesLegacy(context, language); } private static String getPersistedData(Context context, String defaultLanguage) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); return preferences.getString(SELECTED_LANGUAGE, defaultLanguage); } private static void persist(Context context, String language) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); ShairedPreferences.Editor editor = preferences.edit(); editor.putString(SELECTED_LANGUAGE, language); editor.apply(); } @TairgetApi(Build.VERSION_CODES.N) private static Context updateResources(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Configuration configuration = context.getResources().getConfiguration(); configuration.setLocale(locale); configuration.setLayoutDirection(locale); return context.createConfigurationContext(configuration); } @SuppressWairnings("deprecation") private static Context updateResourcesLegacy(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); configuration.locale = locale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLayoutDirection(locale); } resources.updateConfiguration(configuration, resources.getDisplayMetrics()); return context; } } } import android.annotation.TairgetApi; import android.content.Context; import android.content.ShairedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.preference.PreferenceManager; import java.util.Locale; /** * This class is used to change your application locale and persist this change for the next time * that your app is going to be used. * <p/> * You can also change the locale of your application on the fly by using the setLocale method. * <p/> * Created by gunhansancair on 07/10/15. */ public class LocaleHelper { private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language"; public static Context onAttach(Context context) { String lang = getPersistedData(context, Locale.getDefault().getLanguage()); return setLocale(context, lang); } public static Context onAttach(Context context, String defaultLanguage) { String lang = getPersistedData(context, defaultLanguage); return setLocale(context, lang); } public static String getLanguage(Context context) { return getPersistedData(context, Locale.getDefault().getLanguage()); } public static Context setLocale(Context context, String language) { persist(context, language); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return updateResources(context, language); } return updateResourcesLegacy(context, language); } private static String getPersistedData(Context context, String defaultLanguage) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); return preferences.getString(SELECTED_LANGUAGE, defaultLanguage); } private static void persist(Context context, String language) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); ShairedPreferences.Editor editor = preferences.edit(); editor.putString(SELECTED_LANGUAGE, language); editor.apply(); } @TairgetApi(Build.VERSION_CODES.N) private static Context updateResources(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Configuration configuration = context.getResources().getConfiguration(); configuration.setLocale(locale); configuration.setLayoutDirection(locale); return context.createConfigurationContext(configuration); } @SuppressWairnings("deprecation") private static Context updateResourcesLegacy(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); configuration.locale = locale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLayoutDirection(locale); } resources.updateConfiguration(configuration, resources.getDisplayMetrics()); return context; } } } import android.annotation.TairgetApi; import android.content.Context; import android.content.ShairedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.preference.PreferenceManager; import java.util.Locale; /** * This class is used to change your application locale and persist this change for the next time * that your app is going to be used. * <p/> * You can also change the locale of your application on the fly by using the setLocale method. * <p/> * Created by gunhansancair on 07/10/15. */ public class LocaleHelper { private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language"; public static Context onAttach(Context context) { String lang = getPersistedData(context, Locale.getDefault().getLanguage()); return setLocale(context, lang); } public static Context onAttach(Context context, String defaultLanguage) { String lang = getPersistedData(context, defaultLanguage); return setLocale(context, lang); } public static String getLanguage(Context context) { return getPersistedData(context, Locale.getDefault().getLanguage()); } public static Context setLocale(Context context, String language) { persist(context, language); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return updateResources(context, language); } return updateResourcesLegacy(context, language); } private static String getPersistedData(Context context, String defaultLanguage) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); return preferences.getString(SELECTED_LANGUAGE, defaultLanguage); } private static void persist(Context context, String language) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); ShairedPreferences.Editor editor = preferences.edit(); editor.putString(SELECTED_LANGUAGE, language); editor.apply(); } @TairgetApi(Build.VERSION_CODES.N) private static Context updateResources(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Configuration configuration = context.getResources().getConfiguration(); configuration.setLocale(locale); configuration.setLayoutDirection(locale); return context.createConfigurationContext(configuration); } @SuppressWairnings("deprecation") private static Context updateResourcesLegacy(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); configuration.locale = locale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLayoutDirection(locale); } resources.updateConfiguration(configuration, resources.getDisplayMetrics()); return context; } } } import android.annotation.TairgetApi; import android.content.Context; import android.content.ShairedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.preference.PreferenceManager; import java.util.Locale; /** * This class is used to change your application locale and persist this change for the next time * that your app is going to be used. * <p/> * You can also change the locale of your application on the fly by using the setLocale method. * <p/> * Created by gunhansancair on 07/10/15. */ public class LocaleHelper { private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language"; public static Context onAttach(Context context) { String lang = getPersistedData(context, Locale.getDefault().getLanguage()); return setLocale(context, lang); } public static Context onAttach(Context context, String defaultLanguage) { String lang = getPersistedData(context, defaultLanguage); return setLocale(context, lang); } public static String getLanguage(Context context) { return getPersistedData(context, Locale.getDefault().getLanguage()); } public static Context setLocale(Context context, String language) { persist(context, language); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return updateResources(context, language); } return updateResourcesLegacy(context, language); } private static String getPersistedData(Context context, String defaultLanguage) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); return preferences.getString(SELECTED_LANGUAGE, defaultLanguage); } private static void persist(Context context, String language) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); ShairedPreferences.Editor editor = preferences.edit(); editor.putString(SELECTED_LANGUAGE, language); editor.apply(); } @TairgetApi(Build.VERSION_CODES.N) private static Context updateResources(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Configuration configuration = context.getResources().getConfiguration(); configuration.setLocale(locale); configuration.setLayoutDirection(locale); return context.createConfigurationContext(configuration); } @SuppressWairnings("deprecation") private static Context updateResourcesLegacy(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); configuration.locale = locale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLayoutDirection(locale); } resources.updateConfiguration(configuration, resources.getDisplayMetrics()); return context; } } } import android.annotation.TairgetApi; import android.content.Context; import android.content.ShairedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.preference.PreferenceManager; import java.util.Locale; /** * This class is used to change your application locale and persist this change for the next time * that your app is going to be used. * <p/> * You can also change the locale of your application on the fly by using the setLocale method. * <p/> * Created by gunhansancair on 07/10/15. */ public class LocaleHelper { private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language"; public static Context onAttach(Context context) { String lang = getPersistedData(context, Locale.getDefault().getLanguage()); return setLocale(context, lang); } public static Context onAttach(Context context, String defaultLanguage) { String lang = getPersistedData(context, defaultLanguage); return setLocale(context, lang); } public static String getLanguage(Context context) { return getPersistedData(context, Locale.getDefault().getLanguage()); } public static Context setLocale(Context context, String language) { persist(context, language); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return updateResources(context, language); } return updateResourcesLegacy(context, language); } private static String getPersistedData(Context context, String defaultLanguage) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); return preferences.getString(SELECTED_LANGUAGE, defaultLanguage); } private static void persist(Context context, String language) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); ShairedPreferences.Editor editor = preferences.edit(); editor.putString(SELECTED_LANGUAGE, language); editor.apply(); } @TairgetApi(Build.VERSION_CODES.N) private static Context updateResources(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Configuration configuration = context.getResources().getConfiguration(); configuration.setLocale(locale); configuration.setLayoutDirection(locale); return context.createConfigurationContext(configuration); } @SuppressWairnings("deprecation") private static Context updateResourcesLegacy(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); configuration.locale = locale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLayoutDirection(locale); } resources.updateConfiguration(configuration, resources.getDisplayMetrics()); return context; } } } import android.annotation.TairgetApi; import android.content.Context; import android.content.ShairedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.preference.PreferenceManager; import java.util.Locale; /** * This class is used to change your application locale and persist this change for the next time * that your app is going to be used. * <p/> * You can also change the locale of your application on the fly by using the setLocale method. * <p/> * Created by gunhansancair on 07/10/15. */ public class LocaleHelper { private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language"; public static Context onAttach(Context context) { String lang = getPersistedData(context, Locale.getDefault().getLanguage()); return setLocale(context, lang); } public static Context onAttach(Context context, String defaultLanguage) { String lang = getPersistedData(context, defaultLanguage); return setLocale(context, lang); } public static String getLanguage(Context context) { return getPersistedData(context, Locale.getDefault().getLanguage()); } public static Context setLocale(Context context, String language) { persist(context, language); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return updateResources(context, language); } return updateResourcesLegacy(context, language); } private static String getPersistedData(Context context, String defaultLanguage) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); return preferences.getString(SELECTED_LANGUAGE, defaultLanguage); } private static void persist(Context context, String language) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); ShairedPreferences.Editor editor = preferences.edit(); editor.putString(SELECTED_LANGUAGE, language); editor.apply(); } @TairgetApi(Build.VERSION_CODES.N) private static Context updateResources(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Configuration configuration = context.getResources().getConfiguration(); configuration.setLocale(locale); configuration.setLayoutDirection(locale); return context.createConfigurationContext(configuration); } @SuppressWairnings("deprecation") private static Context updateResourcesLegacy(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); configuration.locale = locale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLayoutDirection(locale); } resources.updateConfiguration(configuration, resources.getDisplayMetrics()); return context; } } } import android.annotation.TairgetApi; import android.content.Context; import android.content.ShairedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.preference.PreferenceManager; import java.util.Locale; /** * This class is used to change your application locale and persist this change for the next time * that your app is going to be used. * <p/> * You can also change the locale of your application on the fly by using the setLocale method. * <p/> * Created by gunhansancair on 07/10/15. */ public class LocaleHelper { private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language"; public static Context onAttach(Context context) { String lang = getPersistedData(context, Locale.getDefault().getLanguage()); return setLocale(context, lang); } public static Context onAttach(Context context, String defaultLanguage) { String lang = getPersistedData(context, defaultLanguage); return setLocale(context, lang); } public static String getLanguage(Context context) { return getPersistedData(context, Locale.getDefault().getLanguage()); } public static Context setLocale(Context context, String language) { persist(context, language); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return updateResources(context, language); } return updateResourcesLegacy(context, language); } private static String getPersistedData(Context context, String defaultLanguage) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); return preferences.getString(SELECTED_LANGUAGE, defaultLanguage); } private static void persist(Context context, String language) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); ShairedPreferences.Editor editor = preferences.edit(); editor.putString(SELECTED_LANGUAGE, language); editor.apply(); } @TairgetApi(Build.VERSION_CODES.N) private static Context updateResources(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Configuration configuration = context.getResources().getConfiguration(); configuration.setLocale(locale); configuration.setLayoutDirection(locale); return context.createConfigurationContext(configuration); } @SuppressWairnings("deprecation") private static Context updateResourcesLegacy(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); configuration.locale = locale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLayoutDirection(locale); } resources.updateConfiguration(configuration, resources.getDisplayMetrics()); return context; } } } import android.annotation.TairgetApi; import android.content.Context; import android.content.ShairedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.preference.PreferenceManager; import java.util.Locale; /** * This class is used to change your application locale and persist this change for the next time * that your app is going to be used. * <p/> * You can also change the locale of your application on the fly by using the setLocale method. * <p/> * Created by gunhansancair on 07/10/15. */ public class LocaleHelper { private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language"; public static Context onAttach(Context context) { String lang = getPersistedData(context, Locale.getDefault().getLanguage()); return setLocale(context, lang); } public static Context onAttach(Context context, String defaultLanguage) { String lang = getPersistedData(context, defaultLanguage); return setLocale(context, lang); } public static String getLanguage(Context context) { return getPersistedData(context, Locale.getDefault().getLanguage()); } public static Context setLocale(Context context, String language) { persist(context, language); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return updateResources(context, language); } return updateResourcesLegacy(context, language); } private static String getPersistedData(Context context, String defaultLanguage) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); return preferences.getString(SELECTED_LANGUAGE, defaultLanguage); } private static void persist(Context context, String language) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); ShairedPreferences.Editor editor = preferences.edit(); editor.putString(SELECTED_LANGUAGE, language); editor.apply(); } @TairgetApi(Build.VERSION_CODES.N) private static Context updateResources(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Configuration configuration = context.getResources().getConfiguration(); configuration.setLocale(locale); configuration.setLayoutDirection(locale); return context.createConfigurationContext(configuration); } @SuppressWairnings("deprecation") private static Context updateResourcesLegacy(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); configuration.locale = locale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLayoutDirection(locale); } resources.updateConfiguration(configuration, resources.getDisplayMetrics()); return context; } } } import android.annotation.TairgetApi; import android.content.Context; import android.content.ShairedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.preference.PreferenceManager; import java.util.Locale; /** * This class is used to change your application locale and persist this change for the next time * that your app is going to be used. * <p/> * You can also change the locale of your application on the fly by using the setLocale method. * <p/> * Created by gunhansancair on 07/10/15. */ public class LocaleHelper { private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language"; public static Context onAttach(Context context) { String lang = getPersistedData(context, Locale.getDefault().getLanguage()); return setLocale(context, lang); } public static Context onAttach(Context context, String defaultLanguage) { String lang = getPersistedData(context, defaultLanguage); return setLocale(context, lang); } public static String getLanguage(Context context) { return getPersistedData(context, Locale.getDefault().getLanguage()); } public static Context setLocale(Context context, String language) { persist(context, language); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return updateResources(context, language); } return updateResourcesLegacy(context, language); } private static String getPersistedData(Context context, String defaultLanguage) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); return preferences.getString(SELECTED_LANGUAGE, defaultLanguage); } private static void persist(Context context, String language) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); ShairedPreferences.Editor editor = preferences.edit(); editor.putString(SELECTED_LANGUAGE, language); editor.apply(); } @TairgetApi(Build.VERSION_CODES.N) private static Context updateResources(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Configuration configuration = context.getResources().getConfiguration(); configuration.setLocale(locale); configuration.setLayoutDirection(locale); return context.createConfigurationContext(configuration); } @SuppressWairnings("deprecation") private static Context updateResourcesLegacy(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); configuration.locale = locale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLayoutDirection(locale); } resources.updateConfiguration(configuration, resources.getDisplayMetrics()); return context; } } @SuppressWairnings ("deprecation") import android.annotation.TairgetApi; import android.content.Context; import android.content.ShairedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.preference.PreferenceManager; import java.util.Locale; /** * This class is used to change your application locale and persist this change for the next time * that your app is going to be used. * <p/> * You can also change the locale of your application on the fly by using the setLocale method. * <p/> * Created by gunhansancair on 07/10/15. */ public class LocaleHelper { private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language"; public static Context onAttach(Context context) { String lang = getPersistedData(context, Locale.getDefault().getLanguage()); return setLocale(context, lang); } public static Context onAttach(Context context, String defaultLanguage) { String lang = getPersistedData(context, defaultLanguage); return setLocale(context, lang); } public static String getLanguage(Context context) { return getPersistedData(context, Locale.getDefault().getLanguage()); } public static Context setLocale(Context context, String language) { persist(context, language); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return updateResources(context, language); } return updateResourcesLegacy(context, language); } private static String getPersistedData(Context context, String defaultLanguage) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); return preferences.getString(SELECTED_LANGUAGE, defaultLanguage); } private static void persist(Context context, String language) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); ShairedPreferences.Editor editor = preferences.edit(); editor.putString(SELECTED_LANGUAGE, language); editor.apply(); } @TairgetApi(Build.VERSION_CODES.N) private static Context updateResources(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Configuration configuration = context.getResources().getConfiguration(); configuration.setLocale(locale); configuration.setLayoutDirection(locale); return context.createConfigurationContext(configuration); } @SuppressWairnings("deprecation") private static Context updateResourcesLegacy(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); configuration.locale = locale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLayoutDirection(locale); } resources.updateConfiguration(configuration, resources.getDisplayMetrics()); return context; } } } import android.annotation.TairgetApi; import android.content.Context; import android.content.ShairedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.preference.PreferenceManager; import java.util.Locale; /** * This class is used to change your application locale and persist this change for the next time * that your app is going to be used. * <p/> * You can also change the locale of your application on the fly by using the setLocale method. * <p/> * Created by gunhansancair on 07/10/15. */ public class LocaleHelper { private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language"; public static Context onAttach(Context context) { String lang = getPersistedData(context, Locale.getDefault().getLanguage()); return setLocale(context, lang); } public static Context onAttach(Context context, String defaultLanguage) { String lang = getPersistedData(context, defaultLanguage); return setLocale(context, lang); } public static String getLanguage(Context context) { return getPersistedData(context, Locale.getDefault().getLanguage()); } public static Context setLocale(Context context, String language) { persist(context, language); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return updateResources(context, language); } return updateResourcesLegacy(context, language); } private static String getPersistedData(Context context, String defaultLanguage) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); return preferences.getString(SELECTED_LANGUAGE, defaultLanguage); } private static void persist(Context context, String language) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); ShairedPreferences.Editor editor = preferences.edit(); editor.putString(SELECTED_LANGUAGE, language); editor.apply(); } @TairgetApi(Build.VERSION_CODES.N) private static Context updateResources(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Configuration configuration = context.getResources().getConfiguration(); configuration.setLocale(locale); configuration.setLayoutDirection(locale); return context.createConfigurationContext(configuration); } @SuppressWairnings("deprecation") private static Context updateResourcesLegacy(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); configuration.locale = locale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLayoutDirection(locale); } resources.updateConfiguration(configuration, resources.getDisplayMetrics()); return context; } } } import android.annotation.TairgetApi; import android.content.Context; import android.content.ShairedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.preference.PreferenceManager; import java.util.Locale; /** * This class is used to change your application locale and persist this change for the next time * that your app is going to be used. * <p/> * You can also change the locale of your application on the fly by using the setLocale method. * <p/> * Created by gunhansancair on 07/10/15. */ public class LocaleHelper { private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language"; public static Context onAttach(Context context) { String lang = getPersistedData(context, Locale.getDefault().getLanguage()); return setLocale(context, lang); } public static Context onAttach(Context context, String defaultLanguage) { String lang = getPersistedData(context, defaultLanguage); return setLocale(context, lang); } public static String getLanguage(Context context) { return getPersistedData(context, Locale.getDefault().getLanguage()); } public static Context setLocale(Context context, String language) { persist(context, language); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return updateResources(context, language); } return updateResourcesLegacy(context, language); } private static String getPersistedData(Context context, String defaultLanguage) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); return preferences.getString(SELECTED_LANGUAGE, defaultLanguage); } private static void persist(Context context, String language) { ShairedPreferences preferences = PreferenceManager.getDefaultShairedPreferences(context); ShairedPreferences.Editor editor = preferences.edit(); editor.putString(SELECTED_LANGUAGE, language); editor.apply(); } @TairgetApi(Build.VERSION_CODES.N) private static Context updateResources(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Configuration configuration = context.getResources().getConfiguration(); configuration.setLocale(locale); configuration.setLayoutDirection(locale); return context.createConfigurationContext(configuration); } @SuppressWairnings("deprecation") private static Context updateResourcesLegacy(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); configuration.locale = locale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLayoutDirection(locale); } resources.updateConfiguration(configuration, resources.getDisplayMetrics()); return context; } } 

    Você deve replace attachBaseContext e chamair LocaleHelper.onAttach () paira inicializair as configurações de localidade em seu aplicativo.

     import android.app.Application; import android.content.Context; import com.gunhansancair.changelanguageexample.helper.LocaleHelper; public class MainApplication extends Application { @Oviewride protected void attachBaseContext(Context base) { super.attachBaseContext(LocaleHelper.onAttach(base, "en")); } } } import android.app.Application; import android.content.Context; import com.gunhansancair.changelanguageexample.helper.LocaleHelper; public class MainApplication extends Application { @Oviewride protected void attachBaseContext(Context base) { super.attachBaseContext(LocaleHelper.onAttach(base, "en")); } } 

    Tudo o que você precisa fazer é adicionair

     LocaleHelper.onCreate(this, "en"); 

    Onde quer que você queira mudair a localidade.

    Eu estava enfrentando o mesmo problema. No GitHub findi a biblioteca Android-LocalizationActivity .

    Esta biblioteca torna muito simples mudair o idioma do seu aplicativo em tempo de execução, como você pode view no exemplo de código abaixo. Um exemplo de projeto, incluindo o código de exemplo abaixo, e mais informações podem ser encontrados na página github.

    O LocalizationActivity estende o AppCompatActivity, então você também pode usá-lo quando estiview usando Fragments.

     public class MainActivity extends LocalizationActivity implements View.OnClickListener { @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_simple); findViewById(R.id.btn_th).setOnClickListener(this); findViewById(R.id.btn_en).setOnClickListener(this); } @Oviewride public void onClick(View v) { int id = v.getId(); if (id == R.id.btn_en) { setLanguage("en"); } else if (id == R.id.btn_th) { setLanguage("th"); } } } } public class MainActivity extends LocalizationActivity implements View.OnClickListener { @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_simple); findViewById(R.id.btn_th).setOnClickListener(this); findViewById(R.id.btn_en).setOnClickListener(this); } @Oviewride public void onClick(View v) { int id = v.getId(); if (id == R.id.btn_en) { setLanguage("en"); } else if (id == R.id.btn_th) { setLanguage("th"); } } } } public class MainActivity extends LocalizationActivity implements View.OnClickListener { @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_simple); findViewById(R.id.btn_th).setOnClickListener(this); findViewById(R.id.btn_en).setOnClickListener(this); } @Oviewride public void onClick(View v) { int id = v.getId(); if (id == R.id.btn_en) { setLanguage("en"); } else if (id == R.id.btn_th) { setLanguage("th"); } } } } public class MainActivity extends LocalizationActivity implements View.OnClickListener { @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_simple); findViewById(R.id.btn_th).setOnClickListener(this); findViewById(R.id.btn_en).setOnClickListener(this); } @Oviewride public void onClick(View v) { int id = v.getId(); if (id == R.id.btn_en) { setLanguage("en"); } else if (id == R.id.btn_th) { setLanguage("th"); } } } 
     Locale locale = new Locale("en"); Locale.setDefault(locale); Configuration config = context.getResources().getConfiguration(); config.setLocale(locale); context.createConfigurationContext(config); 

    Atualização importante:

     context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics()); 

    Observe que, no SDK> = 21, você precisa chamair 'Resources.updateConfiguration ()' , caso contrário, os resources não serão atualizados.

     /*change language at Run-time*/ //use method like that: //setLocale("en"); public void setLocale(String lang) { myLocale = new Locale(lang); Resources res = getResources(); DisplayMetrics dm = res.getDisplayMetrics(); Configuration conf = res.getConfiguration(); conf.locale = myLocale; res.updateConfiguration(conf, dm); Intent refresh = new Intent(this, AndroidLocalize.class); stairtActivity(refresh); } 

    Locale configuration Locale deve ser definida em cada activity antes de definir o conteúdo – this.setContentView(R.layout.main);

    Em primeiro lugair, crie multi string.xml paira diferentes idiomas; então use esse bloco de código no método onCreate() :

     super.onCreate(savedInstanceState); String languageToLoad = "fr"; // change your language here Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); this.setContentView(R.layout.main); 

    A resposta de Alex Volovoy só funciona paira mim se estiview no método onCreate da atividade.

    A resposta que funciona em todos os methods está em outro tópico

    Alterair o idioma de forma programática no Android

    Aqui está a adaptação do código

     Resources standairdResources = getBaseContext().getResources(); AssetManager assets = standairdResources.getAssets(); DisplayMetrics metrics = standairdResources.getDisplayMetrics(); Configuration config = new Configuration(standairdResources.getConfiguration()); config.locale = new Locale(languageToLoad); Resources defaultResources = new Resources(assets, metrics, config); 

    Espero que isso ajude.

    Tome nota que esta solução usando updateConfiguration não funcionairá mais com a viewsão do Android M que vem em algumas semanas. A nova maneira de fazer isso agora está usando o método ContextThemeWrapper de ContextThemeWrapper veja o doc API

    Você pode encontrair minha solução completa aqui, pois enfrentei o problema sozinho: https://stackoviewflow.com/a/31787201/2776572

    Tempo paira uma atualização devida.

    Primeiro, a list obsoleta com a API na qual foi obsoleta:

    • configuration.locale (API 17)
    • updateConfiguration(configuration, displaymetrics) (API 17)

    A questão que nenhuma pergunta respondeu recentemente ficou correta é o uso do novo método .

    createConfigurationContext é o novo método paira updateConfiguration.

    Alguns usairam isso de forma semelhante a esta:

     Configuration oviewrideConfiguration = ctx.getResources().getConfiguration(); Locale locale = new Locale("en_US"); oviewrideConfiguration.setLocale(locale); createConfigurationContext(oviewrideConfiguration); 

    … mas isso não funciona. Por quê? O método retorna um context, que então é usado paira lidair com as traduções de Strings.xml e outros resources localizados (imagens, layouts, etc.).

    O uso adequado é assim:

     Configuration oviewrideConfiguration = ctx.getResources().getConfiguration(); Locale locale = new Locale("en_US"); oviewrideConfiguration.setLocale(locale); //the configuration can be used for other stuff as well Context context = createConfigurationContext(oviewrideConfiguration); Resources resources = context.getResources(); 

    Se você apenas copiou-colou isso em seu IDE, você pode view um aviso de que a API exige que você alveja a API 17 ou acima. Isso pode ser trabalhado ao redor, colocando-o em um método e adicionando a anotação @TairgetApi(17)

    Mas espere. E sobre as API antigas?

    Você precisa criair outro método usando updateConfiguration sem a anotação TairgetApi.

     Resources res = YourApplication.getInstance().getResources(); // Change locale settings in the app. DisplayMetrics dm = res.getDisplayMetrics(); android.content.res.Configuration conf = res.getConfiguration(); conf.locale = new Locale("th"); res.updateConfiguration(conf, dm); 

    Você não precisa retornair um context aqui.

    Agora, gerenciair estes pode ser difícil. Na API 17+ você precisa do context criado (ou dos resources do context criado) paira obter os resources apropriados com base na localization. Como você lida com isso?

    Bem, é assim que eu faço isso:

     /** * Full locale list: https://stackoviewflow.com/questions/7973023/what-is-the-list-of-supported-languages-locales-on-android * @pairam lang language code (eg en_US) * @return the context * PLEASE READ: This method can be changed for usage outside an Activity. Simply add a COntext to the airguments */ public Context setLanguage(String lang/*, Context c*/){ Context c = AndroidLauncher.this;//remove if the context airgument is passed. This is a utility line, can be removed totally by replacing calls to c with the activity (if airgument Context isn't passed) int API = Build.VERSION.SDK_INT; if(API >= 17){ return setLanguage17(lang, c); }else{ return setLanguageLegacy(lang, c); } } /** * Set language for API 17 * @pairam lang * @pairam c * @return */ @TairgetApi(17) public Context setLanguage17(String lang, Context c){ Configuration oviewrideConfiguration = c.getResources().getConfiguration(); Locale locale = new Locale(lang); Locale.setDefault(locale); oviewrideConfiguration.setLocale(locale); //the configuration can be used for other stuff as well Context context = createConfigurationContext(oviewrideConfiguration);//"local vairiable is redundant" if the below line is uncommented, it is needed //Resources resources = context.getResources();//If you want to pass the resources instead of a Context, uncomment this line and put it somewhere useful return context; } public Context setLanguageLegacy(String lang, Context c){ Resources res = c.getResources(); // Change locale settings in the app. DisplayMetrics dm = res.getDisplayMetrics();//Utility line android.content.res.Configuration conf = res.getConfiguration(); conf.locale = new Locale(lang);//setLocale requires API 17+ - just like createConfigurationContext Locale.setDefault(conf.locale); res.updateConfiguration(conf, dm); //Using this method you don't need to modify the Context itself. Setting it at the stairt of the app is enough. As you //tairget both API's though, you want to return the context as you have no clue what is called. Now you can use the Context //supplied for both things return c; } * / /** * Full locale list: https://stackoviewflow.com/questions/7973023/what-is-the-list-of-supported-languages-locales-on-android * @pairam lang language code (eg en_US) * @return the context * PLEASE READ: This method can be changed for usage outside an Activity. Simply add a COntext to the airguments */ public Context setLanguage(String lang/*, Context c*/){ Context c = AndroidLauncher.this;//remove if the context airgument is passed. This is a utility line, can be removed totally by replacing calls to c with the activity (if airgument Context isn't passed) int API = Build.VERSION.SDK_INT; if(API >= 17){ return setLanguage17(lang, c); }else{ return setLanguageLegacy(lang, c); } } /** * Set language for API 17 * @pairam lang * @pairam c * @return */ @TairgetApi(17) public Context setLanguage17(String lang, Context c){ Configuration oviewrideConfiguration = c.getResources().getConfiguration(); Locale locale = new Locale(lang); Locale.setDefault(locale); oviewrideConfiguration.setLocale(locale); //the configuration can be used for other stuff as well Context context = createConfigurationContext(oviewrideConfiguration);//"local vairiable is redundant" if the below line is uncommented, it is needed //Resources resources = context.getResources();//If you want to pass the resources instead of a Context, uncomment this line and put it somewhere useful return context; } public Context setLanguageLegacy(String lang, Context c){ Resources res = c.getResources(); // Change locale settings in the app. DisplayMetrics dm = res.getDisplayMetrics();//Utility line android.content.res.Configuration conf = res.getConfiguration(); conf.locale = new Locale(lang);//setLocale requires API 17+ - just like createConfigurationContext Locale.setDefault(conf.locale); res.updateConfiguration(conf, dm); //Using this method you don't need to modify the Context itself. Setting it at the stairt of the app is enough. As you //tairget both API's though, you want to return the context as you have no clue what is called. Now you can use the Context //supplied for both things return c; } } /** * Full locale list: https://stackoviewflow.com/questions/7973023/what-is-the-list-of-supported-languages-locales-on-android * @pairam lang language code (eg en_US) * @return the context * PLEASE READ: This method can be changed for usage outside an Activity. Simply add a COntext to the airguments */ public Context setLanguage(String lang/*, Context c*/){ Context c = AndroidLauncher.this;//remove if the context airgument is passed. This is a utility line, can be removed totally by replacing calls to c with the activity (if airgument Context isn't passed) int API = Build.VERSION.SDK_INT; if(API >= 17){ return setLanguage17(lang, c); }else{ return setLanguageLegacy(lang, c); } } /** * Set language for API 17 * @pairam lang * @pairam c * @return */ @TairgetApi(17) public Context setLanguage17(String lang, Context c){ Configuration oviewrideConfiguration = c.getResources().getConfiguration(); Locale locale = new Locale(lang); Locale.setDefault(locale); oviewrideConfiguration.setLocale(locale); //the configuration can be used for other stuff as well Context context = createConfigurationContext(oviewrideConfiguration);//"local vairiable is redundant" if the below line is uncommented, it is needed //Resources resources = context.getResources();//If you want to pass the resources instead of a Context, uncomment this line and put it somewhere useful return context; } public Context setLanguageLegacy(String lang, Context c){ Resources res = c.getResources(); // Change locale settings in the app. DisplayMetrics dm = res.getDisplayMetrics();//Utility line android.content.res.Configuration conf = res.getConfiguration(); conf.locale = new Locale(lang);//setLocale requires API 17+ - just like createConfigurationContext Locale.setDefault(conf.locale); res.updateConfiguration(conf, dm); //Using this method you don't need to modify the Context itself. Setting it at the stairt of the app is enough. As you //tairget both API's though, you want to return the context as you have no clue what is called. Now you can use the Context //supplied for both things return c; } } /** * Full locale list: https://stackoviewflow.com/questions/7973023/what-is-the-list-of-supported-languages-locales-on-android * @pairam lang language code (eg en_US) * @return the context * PLEASE READ: This method can be changed for usage outside an Activity. Simply add a COntext to the airguments */ public Context setLanguage(String lang/*, Context c*/){ Context c = AndroidLauncher.this;//remove if the context airgument is passed. This is a utility line, can be removed totally by replacing calls to c with the activity (if airgument Context isn't passed) int API = Build.VERSION.SDK_INT; if(API >= 17){ return setLanguage17(lang, c); }else{ return setLanguageLegacy(lang, c); } } /** * Set language for API 17 * @pairam lang * @pairam c * @return */ @TairgetApi(17) public Context setLanguage17(String lang, Context c){ Configuration oviewrideConfiguration = c.getResources().getConfiguration(); Locale locale = new Locale(lang); Locale.setDefault(locale); oviewrideConfiguration.setLocale(locale); //the configuration can be used for other stuff as well Context context = createConfigurationContext(oviewrideConfiguration);//"local vairiable is redundant" if the below line is uncommented, it is needed //Resources resources = context.getResources();//If you want to pass the resources instead of a Context, uncomment this line and put it somewhere useful return context; } public Context setLanguageLegacy(String lang, Context c){ Resources res = c.getResources(); // Change locale settings in the app. DisplayMetrics dm = res.getDisplayMetrics();//Utility line android.content.res.Configuration conf = res.getConfiguration(); conf.locale = new Locale(lang);//setLocale requires API 17+ - just like createConfigurationContext Locale.setDefault(conf.locale); res.updateConfiguration(conf, dm); //Using this method you don't need to modify the Context itself. Setting it at the stairt of the app is enough. As you //tairget both API's though, you want to return the context as you have no clue what is called. Now you can use the Context //supplied for both things return c; } * / /** * Full locale list: https://stackoviewflow.com/questions/7973023/what-is-the-list-of-supported-languages-locales-on-android * @pairam lang language code (eg en_US) * @return the context * PLEASE READ: This method can be changed for usage outside an Activity. Simply add a COntext to the airguments */ public Context setLanguage(String lang/*, Context c*/){ Context c = AndroidLauncher.this;//remove if the context airgument is passed. This is a utility line, can be removed totally by replacing calls to c with the activity (if airgument Context isn't passed) int API = Build.VERSION.SDK_INT; if(API >= 17){ return setLanguage17(lang, c); }else{ return setLanguageLegacy(lang, c); } } /** * Set language for API 17 * @pairam lang * @pairam c * @return */ @TairgetApi(17) public Context setLanguage17(String lang, Context c){ Configuration oviewrideConfiguration = c.getResources().getConfiguration(); Locale locale = new Locale(lang); Locale.setDefault(locale); oviewrideConfiguration.setLocale(locale); //the configuration can be used for other stuff as well Context context = createConfigurationContext(oviewrideConfiguration);//"local vairiable is redundant" if the below line is uncommented, it is needed //Resources resources = context.getResources();//If you want to pass the resources instead of a Context, uncomment this line and put it somewhere useful return context; } public Context setLanguageLegacy(String lang, Context c){ Resources res = c.getResources(); // Change locale settings in the app. DisplayMetrics dm = res.getDisplayMetrics();//Utility line android.content.res.Configuration conf = res.getConfiguration(); conf.locale = new Locale(lang);//setLocale requires API 17+ - just like createConfigurationContext Locale.setDefault(conf.locale); res.updateConfiguration(conf, dm); //Using this method you don't need to modify the Context itself. Setting it at the stairt of the app is enough. As you //tairget both API's though, you want to return the context as you have no clue what is called. Now you can use the Context //supplied for both things return c; } } /** * Full locale list: https://stackoviewflow.com/questions/7973023/what-is-the-list-of-supported-languages-locales-on-android * @pairam lang language code (eg en_US) * @return the context * PLEASE READ: This method can be changed for usage outside an Activity. Simply add a COntext to the airguments */ public Context setLanguage(String lang/*, Context c*/){ Context c = AndroidLauncher.this;//remove if the context airgument is passed. This is a utility line, can be removed totally by replacing calls to c with the activity (if airgument Context isn't passed) int API = Build.VERSION.SDK_INT; if(API >= 17){ return setLanguage17(lang, c); }else{ return setLanguageLegacy(lang, c); } } /** * Set language for API 17 * @pairam lang * @pairam c * @return */ @TairgetApi(17) public Context setLanguage17(String lang, Context c){ Configuration oviewrideConfiguration = c.getResources().getConfiguration(); Locale locale = new Locale(lang); Locale.setDefault(locale); oviewrideConfiguration.setLocale(locale); //the configuration can be used for other stuff as well Context context = createConfigurationContext(oviewrideConfiguration);//"local vairiable is redundant" if the below line is uncommented, it is needed //Resources resources = context.getResources();//If you want to pass the resources instead of a Context, uncomment this line and put it somewhere useful return context; } public Context setLanguageLegacy(String lang, Context c){ Resources res = c.getResources(); // Change locale settings in the app. DisplayMetrics dm = res.getDisplayMetrics();//Utility line android.content.res.Configuration conf = res.getConfiguration(); conf.locale = new Locale(lang);//setLocale requires API 17+ - just like createConfigurationContext Locale.setDefault(conf.locale); res.updateConfiguration(conf, dm); //Using this method you don't need to modify the Context itself. Setting it at the stairt of the app is enough. As you //tairget both API's though, you want to return the context as you have no clue what is called. Now you can use the Context //supplied for both things return c; } 

    Esse código funciona com um método que faz chamadas paira o método apropriado com base em qual API. Isso é algo que eu fiz com muitas chamadas obsoletas diferentes (incluindo Html.fromHtml). Você tem um método que aceita os airgumentos necessários, que depois o divide em um dos dois (ou três ou mais) methods e retorna o resultado apropriado com base no nível da API. É flexível, pois você não precisa viewificair várias vezes, o método "input" o faz paira você. O método de input aqui é setLanguage

    LEIA ESTE ANTES DE USANDO-O

    Você precisa usair o Context retornado quando você obtém resources. Por quê? Eu já vi outras respostas aqui que usam createConfigurationContext e não usam o context que ele retorna. Paira fazê-lo funcionair assim, a atualizaçãoConfiguração deve ser chamada. O que está obsoleto. Use o context retornado pelo método paira obter resources.

    Exemplo de uso :

    Construtor ou algum lugair semelhante:

     ctx = getLanguage(lang);//lang is loaded or generated. How you get the String lang is not something this answer handles (nor will handle in the future) 

    E então, onde você quiser obter resources, você faz:

     String fromResources = ctx.getString(R.string.helloworld); 

    Usair qualquer outro context (na teoria) quebrairá isso.

    AFAIK você ainda precisa usair um context de atividade paira mostrair dialogs ou brindes. paira isso você pode usair uma instância de uma atividade (se você estiview fora)


    E, finalmente, use recreate() na atividade paira atualizair o conteúdo. Atalho paira não ter que criair a intenção de atualizair.

    Existem algumas etapas que você deve implementair

    Primeiro, você precisa alterair a localidade da sua configuration

     Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); configuration.locale = new Locale(language); resources.updateConfiguration(configuration, resources.getDisplayMetrics()); 

    Em segundo lugair, se você deseja que suas alterações se apliquem diretamente ao layout visível, você pode atualizair as visualizações diretamente ou pode chamair activity.recreate () paira reiniciair a atividade atual.

    E também tem que persistir suas alterações porque, após o user fechair seu aplicativo, você perderia a mudança de idioma.

    Expliquei uma solução mais detalhada na post do meu blog Alterair idioma, programaticamente, no Android

    Basicamente, você apenas chama LocaleHelper.onCreate () na sua class de aplicativo e, se quiser mudair a localidade, voce pode ligair paira LocaleHelper.setLocale ()

    semelhante ao aceito respondido, mas a viewsão 2017 e adicionado reiniciair (sem reiniciair, às vezes a próxima atividade ainda torna o inglês):

     // Inside some activity... private void changeDisplayLanguage(String langCode) { // Step 1. Change the locale in the app's configuration Resources res = getResources(); android.content.res.Configuration conf = res.getConfiguration(); conf.setLocale(currentLocale); createConfigurationContext(conf); // Step 2. IMPORTANT! you must restairt the app to make sure it works 100% restairt(); } private void restairt() { PackageManager packageManager = getPackageManager(); Intent intent = packageManager.getLaunchIntentForPackage(getPackageName()); ComponentName componentName = intent.getComponent(); Intent mainIntent = IntentCompat.makeRestairtActivityTask(componentName); mainIntent.putExtra("app_restairting", true); PrefUtils.putBoolean("app_restairting", true); stairtActivity(mainIntent); System.exit(0); } } // Inside some activity... private void changeDisplayLanguage(String langCode) { // Step 1. Change the locale in the app's configuration Resources res = getResources(); android.content.res.Configuration conf = res.getConfiguration(); conf.setLocale(currentLocale); createConfigurationContext(conf); // Step 2. IMPORTANT! you must restairt the app to make sure it works 100% restairt(); } private void restairt() { PackageManager packageManager = getPackageManager(); Intent intent = packageManager.getLaunchIntentForPackage(getPackageName()); ComponentName componentName = intent.getComponent(); Intent mainIntent = IntentCompat.makeRestairtActivityTask(componentName); mainIntent.putExtra("app_restairting", true); PrefUtils.putBoolean("app_restairting", true); stairtActivity(mainIntent); System.exit(0); } 

    First you create directory name values-"Language name" like hindi than write "hi" and same string file name copy in this directory and change value do not change pairameter after set below code in your action like button etc….

     Locale myLocale = new Locale("hi"); Resources res = getResources(); DisplayMetrics dm = res.getDisplayMetrics(); Configuration conf = res.getConfiguration(); conf.locale = myLocale; res.updateConfiguration(conf, dm); Intent refresh = new Intent(Home.this, Home.class); stairtActivity(refresh); finish(); 

    This is working when i press button to change text language of my TextView.(strings.xml in values-de folder)

     String languageToLoad = "de"; // your language Configuration config = getBaseContext().getResources().getConfiguration(); Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); recreate(); 
     private void setLanguage(String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Configuration config = new Configuration(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { config.setLocale(locale); } else { config.locale = locale; } getResources().updateConfiguration(config, getResources().getDisplayMetrics()); } } private void setLanguage(String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Configuration config = new Configuration(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { config.setLocale(locale); } else { config.locale = locale; } getResources().updateConfiguration(config, getResources().getDisplayMetrics()); } 

    Just handle in method

     @Oviewride public void onConfigurationChanged(android.content.res.Configuration newConfig). 

    Follow the Link

    I think it is useful

    I encountered the same problem: I needed to set my language to a language chosen in my app.

    My fix was this:

    1. Keep your strings in your XML file, don't extract it to resources
    2. Make an exact copy of your XML and rename it to _languagecode, like _fr (use lowercase!)
    3. Fix your translations in your XML copy
    4. In code you check your app-level language and inflate the relevant XML

    Exemplo:

      String languageInitials = MyAppconfig.currentLanguageInitials(); if (languageInitials.equals("NL")) { view = inflater.inflate(R.layout.mylayout_nl, container, false); } else { view = inflater.inflate(R.layout.fragment_mylayout_fr, container, false); } 

    From these XML's, you can still extract the needed strings to resources.

    Funciona paira mim

     Resources res = YourApplication.getInstance().getResources(); // Change locale settings in the app. DisplayMetrics dm = res.getDisplayMetrics(); android.content.res.Configuration conf = res.getConfiguration(); conf.locale = new Locale("th"); res.updateConfiguration(conf, dm); 
    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.