Change locale within an Android application

I wanted users to have the ability to change application locale. Took me hours, but finally this is the code to do it. goBack() method forces a refreshment of strings among application visual elements.



public class LanguageMenu extends Activity{

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_language_menu);
	}
	
	public void selectEnglish (View view)
	{
		selectLanguage(new Locale("en"));
		goBack();
	}
	public void selectSpanish (View view)
	{
		selectLanguage(new Locale("es"));
		goBack();
	}
	public void selectItalian (View view)
	{
		selectLanguage(new Locale("it"));
		goBack();
	}
	public void selectPortuguese (View view)
	{
		selectLanguage(new Locale("pt"));
		goBack();
	}
	public void selectDutch (View view)
	{
		selectLanguage(new Locale("nl"));
		goBack();
	}
	public void selectLanguage(Locale locale)
	{
		Locale.setDefault(locale);
		Configuration config = new Configuration();
		config.locale = locale;
		getBaseContext().getResources().updateConfiguration(
				config, 
				getBaseContext().getResources().getDisplayMetrics());
	}
	public void goBack()
	{
		int activity_id = getIntent().getIntExtra("calling-activity", 0);
		Intent intent = null;
		switch(activity_id)
		{
			case ActivityConstants.ACTIVITY_QUESTIONS:
				intent = new Intent(this, QuestionScreen.class);
			break;
			case ActivityConstants.ACTIVITY_RESULTS:
				intent = new Intent(this, ResultsScreen.class);
			break;
			case ActivityConstants.ACTIVITY_SPLASH:
				intent = new Intent(this, SplashScreen.class);
			break;
		}
		startActivity(intent);
	}
}


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s