如何支持多种设备-语言篇

android设备种类繁多,包括各种各样的形状与尺寸,所以一个优秀的android app应该能够适用各种android设备。

1、支持不同的语言

将界面上显示的字符串从代码中提取出来,放在一个专门的文件中保存是一个非常好的主意。android把它保存在res/values/strings.xml中。

针对不同的语言,我们可以在res/文件夹下面创建各个语言版本的子values文件夹来保存相应的语言,子文件夹命名规则为values-语言种别code。如下面所示

MyProject/
    res/
       values/
           strings.xml
       values-es/
           strings.xml
       values-fr/
           strings.xml
res/values/strings.xml中保存的是英语,res/values-es/strings.xml中保存的是西班牙语,res/values-fr/strings.xml中保存的是法语。

English (default locale), /values/strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title">My Application</string>
    <string name="hello_world">Hello World!</string>
</resources>

Spanish,  /values-es/strings.xml :

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title">Mi Aplicación</string>
    <string name="hello_world">Hola Mundo!</string>
</resources>

French,  /values-fr/strings.xml :

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title">Mon Application</string>
    <string name="hello_world">Bonjour le monde !</string>
</resources>


如何使用这些资源?

正常情况下string资源如何使用,我们就如何使用,不需要我们判断该如何使用哪种语言,因为在程序运行的时候,android系统会根据当前机器语言环境,自动选择对应的string.xml。

For Example:

java code中:

// Get a string resource from your app's Resources
String hello = getResources().getString(R.string.hello_world);

// Or supply a string resource to a method that requires a string
TextView textView = new TextView(this);
textView.setText(R.string.hello_world);

xml code中:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值