Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This code snippet does what you need, I've tested it. Suppose for the example you want the user to be able to switch language through a menu from your main activity. You can do it through saving a language flag as a user preference and check it on "onCreate()" and on "onConfigurationChanged()" as follows:</p> <pre><code> public class MainActivity extends Activity { SharedPreferences mPrefs1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPrefs1 = PreferenceManager.getDefaultSharedPreferences(this); String languageToLoad = mPrefs1.getString("languagePref", Locale.getDefault().getLanguage()); Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics()); setContentView(R.layout.activity_main); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mPrefs1 = PreferenceManager.getDefaultSharedPreferences(this); String languageToLoad = mPrefs1.getString("languagePref", Locale.getDefault().getLanguage()); Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics()); setContentView(R.layout.activity_main); } // Declaring the Menu options @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } //handle menu item selection public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_switch_language: String languageToLoad = getResources().getString(R.string.switch_language); mPrefs1 = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = mPrefs1.edit(); editor.putString("languagePref", languageToLoad); editor.commit(); // Very important to save the preference finish(); startActivity(getIntent()); return true; default: return super.onOptionsItemSelected(item); } } </code></pre> <p>}</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload