_047_Android_Android(国际化)多语言的实现和切换

原创文章,如有转载,请注明出处:http://blog.csdn.net/myth13141314/article/details/62037194

Android 的多语言设置在开发中时有用到,实现也不复杂,主要包括三个方面

不同语言的资源的实现,即string.xml的实现
利用Locale改变系统的语言设置
首先需要将不同语言版本的资源配置好

新建values文件夹,不同国家的文件夹名字不一样 
根据需要选择建立对应语言的资源文件夹,文件夹名称系统会自动生成 
然后在对应的资源文件夹下面新建string.xml文件,不同语言的字符串资源的名称要一样,如下面的中文和英文:
//英文资源

<resources>
    <string name="app_language">language</string>
</resources>

//中文资源
<resources>
    <string name="app_language">语言</string>
</resources>

通过以上步骤,资源文件已经准备好,接下去就是改变系统的语言环境,这就需要用到Locale

生成新的Locale对象

public Locale(String language, String country) {
        this(language, country, "");
}//例如,生成English,不限地区的Locale对象
new Locale("en", "")

更改系统的语言设置

Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = newLocale;
resources.updateConfiguration(configuration, resources.getDisplayMetrics());//更新配置

需要注意的是,更改语言配置需要在MainActivity的setContentView()之前设置才会起作用

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initLocaleLanguage();
        setContentView(R.layout.activity_main);
    }
}

private void initLocaleLanguage() {
    Resources resources = context.getResources();
    Configuration configuration = resources.getConfiguration();
    configuration.locale = newLocale;
    resources.updateConfiguration(configuration, resources.getDisplayMetrics());//更新配置
}

一般的更改语言的选项都在App的设置里面,改变系统的Locale以后并不会马上生效,需要重启App以后才会有效。如果要及时生效,就需要重启MainActivity,方法如下:

//重启MainActivity
Intent intent = new Intent(SettingActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

猜你喜欢

转载自blog.csdn.net/poiuyppp/article/details/84192482