Wednesday, January 28, 2009

Force Localize an Application on Android

Localization has always been a problem in tech at large and products from big companies like Google, Apple and Microsoft are not immune to it and so does Android (I know they came from Google). But one thing that was cool about Android is it was built for developers to localized their apps by default but the problem is that the API or documentation is lacking. If your in a journey to further localize your application, i suggest you to read this page on the official google groups for developers.

As the title stated, you can force your application to be localize on an application basis and not system basis. In this article we would use simplied chinese and english. To do this you have to edit something on your oncreate function on your default activity.

Update for Android 2.0
Add android:configChanges="locale" to your activity nodes on the manifest file
<activity android:name=".Main" android:configChanges="locale" android:label="@string/app_name" />

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. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String languageToLoad  = "cn";
    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);
  }
}


Quick Explanation
String languageToLoad = "cn";
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);

-- Here we create an new Locale in ch (Simplified Chinese) and set our default locale to a specific locale (See this for more information)

Configuration config = new Configuration();
config.locale = locale;

-- This would create a new Configuration which we would use later and then we change the locale of this configuration with our chinese locale.

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

-- This is the core part, here we only update the configuration of our basecontext's resources. I might not be right here but according to the description of Context, Interface to global information about an application environment. Getting the baseContext should be application level.

Source Code
Main.java
main layout
strings.xml in values folder
strings.xml in values-cn folder

Update History
   Jan 17, 2012 - Visual Update
Post a Comment