android 获取当前系统选择的语言

获取当前系统选择的语言的Java代码:


Locale currentLocale = Locale.getDefault();
String currentLanguage = currentLocale.getLanguage();
String currentCountry = currentLocale.getCountry();
String currentLocaleString = currentLocale.toString();
 

其中,`currentLanguage`为当前语言的ISO 639-1代码,例如:`en`表示英语,`zh`表示中文;`currentCountry`为当前国家的ISO 3166-1代码,例如:`US`表示美国,`CN`表示中国;`currentLocaleString`为当前语言和国家的组合,例如:`en_US`表示美国英语,`zh_CN`表示中国中文。

配置语言的方式:

可以在`res`目录下创建不同语言的资源文件夹,例如:values-en、values-zh等。在这些资源文件夹中创建相同名称的字符串资源文件,例如:strings.xml。然后在每个资源文件中定义对应语言的字符串,例如:

values-en/strings.xml:


<resources>
    <string name="hello_world">Hello World!</string>
</resources>
 

values-zh/strings.xml:


<resources>
    < name="hello_world">你好,世界!</string>
</resources>
 

在程序中使用字符串资源时,系统会自动根据当前语言的设置来选择对应的资源文件。例如:


TextView textView = findViewById(R.id.text_view);
textView.setText(R.string.hello_world);
`

如果当前系统语言为英语,则显示`Hello World!`;如果当前系统语言为中文,则显示`你好,世界!`。 

猜你喜欢

转载自blog.csdn.net/canduecho/article/details/130869303
今日推荐