且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在负载变化的微调不同的strings.xml资源

更新时间:2023-11-15 16:00:28

 私人无效的setLocale(string地区code){
    区域设置区域=新区域(区域code);
    Locale.setDefault(区域);
    配置配置=新配置();
    config.locale =区域;
    。getBaseContext()getResources()updateConfiguration(。配置,getBaseContext()getResources()getDisplayMetrics());
}

在AndroidManifest.xml中的活动标签

 的android:configChanges =语言环境

所以,你onItemSelected()方法应该是这样的:

  @覆盖
公共无效onItemSelected(适配器视图<>为arg0,视图V,INT位置,长ARG3){
    Log.v(价值,语言值:+位置);
    如果(位置== 0){
         的setLocale(EN);
    }
    其他{
         的setLocale(FR);
    }
}

我的答案是基于:


  1. 如何强制语言Android应用程序


  2. Android :应用程序本身内改变区域设置


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

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. Android : changing Locale within the app itself