Multi language android app during Runtime?

柔情痞子 提交于 2019-12-18 09:42:37

问题


My aim is to change an application language from English to Chinese during runtime, is there any suggestions?

 language_spinner = (Spinner)findViewById(R.id.settings_language_spinner);
 language_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                if (pos == 1){
                    Toast.makeText(parent.getContext(),"You have selected English",Toast.LENGTH_SHORT).show();
                    setLocale("en");

                }else if (pos == 2){
                    Toast.makeText(parent.getContext(),"You have selected Chinese",Toast.LENGTH_SHORT).show();
                    setLocale("zh");
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {

            }
        });


    }

    public void setLocale(String lang) {

        myLocale = new Locale(lang);
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        if (!conf.locale.getLanguage().equals(lang)) {
            conf.locale = myLocale;
            res.updateConfiguration(conf, dm);
            Intent refresh = new Intent(this, SettingsActivity.class);
            startActivity(refresh);
            finish();
        }
    }

This code is working properly with English but not working with Chinese please help me in finding the solution ..


回答1:


I can give you idea how you can implement this:

step 1: make string file for all texts in values directory as string-ch, ch is the code for Chinese language. and in code get every string with the getResources.getString(R.string.text_name); so that it can take string value at run time either English or Chinese.

step 2: now create method :

void changeLanguage(String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        getBaseContext().getResources().updateConfiguration(config,
                getBaseContext().getResources().getDisplayMetrics());
    }

step 3: call this method where you want to change language suppose if you want to get changed language of you application according to device language then you can call as:

changeLanguage(Locale.getDefault().getLanguage());


来源:https://stackoverflow.com/questions/45330008/multi-language-android-app-during-runtime

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