Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 多語言切換要點整理

編輯:關於 Android 程式設計

一、切換為英文的程式碼

只要在切換時透過 Locale 與 Configuration 更新資源的語言設定,後續開啟的子視窗就會自動改從 values-en 目錄下的 string.xml 取值:

Locale.setDefault(Locale.ENGLISH);
Configuration config = getBaseContext().getResources().getConfiguration();
config.locale = Locale.ENGLISH;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());

二、Android 的多語言機制:string.xml

Android 靠不同 values 目錄下的 string.xml 來管理多語言。以英文為例,會放在 values-en/string.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Switch Language test</string>
    <string name="title_activity_sub">Sub activity</string>
    <string name="hello_world">Author: canto123</string>
    <string name="Exit">Exit</string>
    <string name="Data">Data=</string>
    <string name="DataTip">Lost data after language switched</string>
</resources>

而 values/string.xml 則是預設語言;如果找不到 values-en 對應的翻譯,系統就會退回使用這裡的字串:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">語言切換實驗</string>
    <string name="hello_world">作者:雜貨鋪</string>
    <string name="menu_settings">Settings</string>
    <string name="Exit">退出</string>
    <string name="Data">數據=</string>
    <string name="title_activity_sub">子頁面</string>
    <string name="DataTip">可以看到切換後,數據丟失</string>
</resources>

三、讓當前頁面立即套用新語言

如果希望切換語言後,目前頁面立刻顯示新語言,就必須重啟當前 Activity:

Intent intent = new Intent();
intent.setClass(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

特別注意:這種做法會讓該頁面的變數值被重新初始化,也就是原本的資料會遺失,實作時需要另外處理狀態保存。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved