Configuring Locale Doesn't work programmatically?

I have an activity where I programmatically set the locale to "de", and it does not work properly and displays the default language (English text), which is set manually. Please, help

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Programmatically sets the locale and language Locale locale = new Locale("de"); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics()); Toast.makeText(getApplicationContext(),Locale.getDefault().getDisplayLanguage(),Toast.LENGTH_LONG).show(); setContentView(R.layout.main); Intent intent=new Intent(LatestLocalizationActivity.this,AnotherActivity.class); startActivity(intent); } 
+4
source share
3 answers

If you added the Strings.xml file to the res-> value-de folder?

 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Programmatically sets the locale and language setContentView(R.layout.main); config = getBaseContext().getResources().getConfiguration(); locale = new Locale("de"); Locale.setDefault(locale); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); refresh(); Toast.makeText(getApplicationContext(),Locale.getDefault().getDisplayLanguage(),Toast.LENGTH_LONG).show(); } @Override public void onConfigurationChanged(Configuration newConfig) { Configuration config = getBaseContext().getResources().getConfiguration(); // refresh your views here Locale.setDefault(locale); config.locale = locale; super.onConfigurationChanged(newConfig); } private void refresh() { finish(); Intent myIntent = new Intent(yourActivity.this, yourActivity.class); startActivity(myIntent); } 
+5
source

Please note that although you may be able to hack something like working on it, Android does not currently support this in a reliable way. In particular, the structure works with the current configuration in resources and will update it when it considers it appropriate. You will struggle with this, and it is unlikely that you will not be able to have situations when the configuration returns to the system language.

+3
source

This worked for me:

 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()); } 

Use your CONTROL OF ACTIVITY, not the context of your application.

+2
source

All Articles