android國際化操作

1、簡單介紹

我們知道在java中通過.properties文件來配置資源文件,一般用的有中文message_zh_CN.properties和英文message_en_US.properties兩個配置文件,然後通過一系列的配置來實現,這裏不詳細介紹,在android也有國際化,而且更方便,因爲android本身採用了Xml資源文件來管理所有的字符串消息,只要爲各消息提供不同語言、國家對應的內容即可。

2、資源文件的編寫

和java中的properties文件一樣,在android也要配置這樣的文件,只不過android是在res/values目錄下編寫字符串消息,爲了給這些消息提供不同的語言、國家的版本,開發者需要在values目錄下添加幾個不同語言國家版本,不同values文件夾的命名方式爲:

  values-語言代碼-r國家代碼

例如:values-zh-rCN(中文)和values-en-rUS(英文)

如果需要讓圖片也實現國際化,還要爲drawable目錄添加幾個不同語言國家的版本,不同drawable文件夾的命名方式爲:drawable-語言代碼-r國家代碼

在values-zh-rCN文件夾下建一個strings.xml代表中文資源

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="ok">確定</string>
    <string name="cancel">取消</string>
    <string name="msg">你好啊,小機器人!</string>
</resources>

在valuesen-rUS文件夾下建一個strings.xml代表英文資源

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="ok">ok</string>
    <string name="cancel">cancel</string>
    <string name="msg">Hello,Android!</string>
</resources>

3、在佈局文件中使用這些字符串資源

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/msg"
        />
    
    <Button 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/ok"
        />
    
    <Button 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/cancel"/>

</LinearLayout>

接着在activity中通過setContentView(R.layout.main)加載佈局文件

運行效果:

首先顯示出來的是英文版的,android模擬器默認英文的,接着我們可以在Setting/Language&Input/Language這將android語言設置問中文的,就可以看到中文版的。

 

發佈了98 篇原創文章 · 獲贊 20 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章