1

I am am trying to change the language of my activity (just the activity not the whole app) when a new item is selected within a spinner. The spinner contains Text representing the language I would like to switch through (French, English etc.)

In my res folder I have separate strings.xml for each language in the correct folders i.e. values-fr for French. How can I, on the changing of the spinner item, load from the correct strings.xml which corresponds?

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ArrayList<String> languages = new ArrayList<String>();
    languages.add("English");
    languages.add("French");

    Spinner spinner = (Spinner)findViewById(R.id.spinner);
    spinner.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, languages));
    spinner.setOnItemSelectedListener(this);
}

@Override
public void onItemSelected(AdapterView<?> arg0, View v, int position, long arg3) {
    Log.v("Value", "Language Value: " + position);
    if(position == 0){
         //Change text to English
    }
    else{
        //Change text to French
    }
}
SamRowley
  • 3,435
  • 7
  • 48
  • 77

1 Answers1

4
private void setLocale(String localeCode){
    Locale locale = new Locale(localeCode);
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale;
    getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}

in AndroidManifest.xml in activity tag

android:configChanges="locale"

So your onItemSelected() method should look like this:

@Override
public void onItemSelected(AdapterView<?> arg0, View v, int position, long arg3) {
    Log.v("Value", "Language Value: " + position);
    if(position == 0){
         setLocale("en");
    }
    else{
         setLocale("fr");
    }
}

My answer is based on:

  1. how to force language in android application

  2. Changing Locale within the app itself

Community
  • 1
  • 1
kamil zych
  • 1,682
  • 13
  • 21
  • I can see where this is coming from but doesn't change the language when the Spinner item is changed. – SamRowley Sep 05 '11 at 10:04
  • No I understood that part of how to actually set the Locale just I have no idea how to refresh the contentView with the new Locale set. – SamRowley Sep 05 '11 at 10:45
  • Do you have android:configChanges="locale" in your AndroidManifest.xml? And also in supportScreens tag you should have android:anyDensity="true". – kamil zych Sep 05 '11 at 11:04