Wednesday, March 21, 2012

Resources based on localization

Hi all!,
Today I will show you a very powerful technique, which we can exploit through localization: resources based on localization.
With the location and the opportunity given by Android to create specific resources based on the localization this powerful technique is very easy to implement.
The example that I will show is to select a language, and display a text according to your choice.
First create many localized folders as many languages ​​we want to support , that is how many languages ​​we want to display our text.
In the example, are 3 languages​​: English (default), Italian and French.




Now we must create a resource file for each localized folder, where we will insert the text as a string resource.
Created our texts, we are going to implement graphically our selection language Activity:



    

    


The Activity has consisted of only one spinner, which allows the choice of language, and a button to start the Activity containing our text:

public class LocalizationUpdaterActivity extends Activity {

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  Spinner spinner = (Spinner) findViewById(R.id.spinner1);
  spinner.setPrompt("select language");

  ArrayAdapter adapter = new ArrayAdapter(this,
    android.R.layout.simple_spinner_item, languages);
  adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  spinner.setAdapter(adapter);

  spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

   public void onItemSelected(AdapterView arg0, View arg1,
     int arg2, long arg3) {
    Configuration config = new Configuration();
    switch (arg2) {
    case 0:
     config.locale = Locale.ENGLISH;
     break;
    case 1:
     config.locale = Locale.ITALIAN;
     break;
    case 2:
     config.locale = Locale.FRENCH;
     break;
    default:
     config.locale = Locale.ENGLISH;
     break;
    }
    getResources().updateConfiguration(config, null);
   }

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

 }
 
 public void onClick(View v){
  startActivity(new Intent(getBaseContext(), TextActivity.class));
 }
 private String[] languages = { "Inglese", "Italiano", "Francese" };
}


We can observe what happens when we click an element in spinner: depending on the item clickedc we understand wich Locale we must create, so then, we invoke the method updateConfiguration to update the resource configuration! WOW!
That is going to change all the values ​​of resources based on location.
The layout of the Activity that shows the text contains only a TextView that refers to our resource of type String, then by the choice of language made ​​we can see the different texts.

Here's a short video:

video



This is the link of source code