在Spinner上加载不同的strings.xml资源

时间:2011-09-05 09:04:34

标签: java android locale

我正在尝试在微调器中选择新项目时更改我的活动语言(只是活动而不是整个应用程序)。微调器包含表示我想要切换的语言的文本(法语,英语等)

在我的res文件夹中,我在正确的文件夹中为每种语言分别使用strings.xml,即为法语的值-fr。在更改微调器项时,如何从正确的strings.xml加载?

@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 个答案:

答案 0 :(得分: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());
}

在AndroidManifest.xml中的活动代码

android:configChanges="locale"

所以你的onItemSelected()方法应如下所示:

@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");
    }
}

我的回答是基于:

  1. how to force language in android application

  2. Changing Locale within the app itself