在运行时使用多语言Android应用程序? [英] Multi language android app during Runtime?

查看:114
本文介绍了在运行时使用多语言Android应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是在运行时将应用程序语言从英语更改为中文,有什么建议吗?

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

推荐答案

我可以告诉您如何实现此目的:

I can give you idea how you can implement this:

步骤1:为values目录中的所有文本创建字符串文件为string-ch,ch是中文代码.并且在代码中使用getResources.getString(R.string.text_name);获取每个字符串,以便它可以在运行时获取英语或中文的字符串值.

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.

步骤2:现在创建方法:

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());
    }

第3步:在要更改语言的位置调用此方法,假设如果您希望根据设备语言获得应用程序的更改语言,则可以按以下方式调用:

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());

这篇关于在运行时使用多语言Android应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆