SamRowley
SamRowley

Reputation: 3485

Load different strings.xml resource on Spinner change

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
    }
}

Upvotes: 1

Views: 3288

Answers (1)

kamil zych
kamil zych

Reputation: 1712

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

Upvotes: 4

Related Questions