Load different strings.xml resource on Spinner change

可紊 提交于 2020-01-03 04:15:02

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/7305928/load-different-strings-xml-resource-on-spinner-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!