Android localization at runtime

In the previous post, the application we created identifies the locale before application is loaded. But in some situation where we need to change the language of the application at runtime or on the go according to the user’s need. You might have seen some application which has dialog or menu which list the languages supported by the application.

On selecting the language from the list, entire application will be applied with the locale/language selected which happens at runtime.

Follow the previous post example, where we are going to add spinner control to display the list of languages and add logic in activity class to handle the locale changes.
Either you can proceed with the below listings, or you can directly download code.

[pgsubscribe]

Quick Links

Code Listings

AndroidLocalize .java

  1. Declare spinner control, locale and button objects
  2. Find the spinner control from main.xml and add OnItemSelectedListener class to it
  3. Based on the list item selected, call setLocale method with the Locale value: English – en, Tamil – ta and Hindi – hi.
  4. Change the configuration of device (add locale) for your application
  5. Make sure that you refresh the current activity to reflect the changes made in configuration.
package com.prgguru.android;

import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class AndroidLocalize extends Activity {
	Spinner spinnerctrl;
	Button btn;
	Locale myLocale;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		spinnerctrl = (Spinner) findViewById(R.id.spinner1);
		spinnerctrl.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {

				if (pos == 1) {

					Toast.makeText(parent.getContext(),
							"You have selected Tamil", Toast.LENGTH_SHORT)
							.show();
					setLocale("ta");
				} else if (pos == 2) {

					Toast.makeText(parent.getContext(),
							"You have selected Hindi", Toast.LENGTH_SHORT)
							.show();
					setLocale("hi");
				} else if (pos == 3) {

					Toast.makeText(parent.getContext(),
							"You have selected English", Toast.LENGTH_SHORT)
							.show();
					setLocale("en");
				}

			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}

		});
	}

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

Demo

Congratulations, We are done.
Let us test the application:
Right click on the project >> Run as >> Android application >> Choose emulator or device
Tap on the button and see what happens.



Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android is the installation file simliar to exe in windows.

[pglinkadssmall1]

I hope you enjoyed the post!! :)

Suggested posts for further reading


[pgfeedback]
[pgwriteforus]

Related Articles

Author: Android Guru

Share This Post On
468 ad
  • Taj Marlow

    I suggest using this localization tool for Android app localization: https://poeditor.com/. It offers translation memory and automatic translation functions.

  • Dennis

    I don’t know if it’s done but wouldn’t it be better to call finish() after “refreshing” in line 70? So that the back-button wouldn’t go through all language changes. In addition wouldn’t it be good to only change the language if the user selects one that isn’t currently active? I did the two things with little changes: My setLocale looks like this:
    public void setLocale(String lang) {
    Resources res = getResources();
    DisplayMetrics dm = res.getDisplayMetrics();
    Configuration conf = res.getConfiguration();
    if (!conf.locale.getLanguage().equals(lang)) {
    conf.locale = new Locale(lang);
    res.updateConfiguration(conf, dm);
    Intent refresh = new Intent(this, AndroidLocalize.class);
    startActivity(refresh);
    finish();
    }
    }

    • That’s really a valuable suggestion. Will update the code and post.

  • amarnath

    Select Language alert dialog displays junk values.
    After selection test also junk.
    Does it require any changes?

    • The application uses English, Tamil and Hindi languages. Please check if your device support these languages. It works well in almost all mobile devices and even tablets.

  • Ken

    That works for the current Activity, but activities I already have open remain in the original language when i return to them. I want the entire app to use the newly selected language DUH, whether the activity was already open or not.

    • Hi,
      As per the logic, it will apply the language only to the application and not to the all applications installed in the phone.
      Thanks.

      • Ken

        I didn’t say all Applications. I said all Activities.

        • As per the logic, language will be applied only to our example activity.

  • Ahmed

    thanks alot for this tutorial. just very small note on the refresh intent it is better that it has the following flag:
    Intent refresh = new Intent(this, Main.class);
    refresh.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(refresh);

    again thank you

  • how can i change language coming from server in English??

    Thanks

  • Tonyoh87

    Your tutorial is great but when trying to implement this into a fragment I totally failed and wasted all my day :(
    http://stackoverflow.com/questions/22741013/spinner-localization-inside-a-fragment

  • Basavaraj Sarwad

    It was very helpful. Can you please let me know how to support Kannada fonts?

Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares