1. 程式人生 > >超詳細!一步一步完成多語言適配

超詳細!一步一步完成多語言適配

多語言適配是工作中經常要用到的,為了怕自己遺忘,也為了大家瞭解一下多語言適配,寫了這篇部落格,話不多說-------------開始吧。

多語言適配分三步 : 1,新建values檔案   2,Java程式碼   3,重新整理頁面

一,新建不同語言的Values檔案

第一步,把左邊的工作區間切換到project , 找到res資料夾下的values 資料夾 複製 , 貼上到res檔案架下面重新命名 如下圖:
點選確定後,在res多出對應資料夾   至於為什麼這麼命名  過一會解釋~ 如下圖:
colors.xml   和  styles.xml  沒有用 刪掉 開啟兩個 strings.xml  新增一條string   方便一會確認

在來個英文的吧     values-en
第一步基本完成   不過順道把 佈局檔案做一下簡單設定吧
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.administrator.q.MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/asd"
        android:textSize="40sp"
        />

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@null"
        android:text="重新整理按鈕"
        android:textSize="40sp"/>


</LinearLayout>


二 , Java 程式碼

Resources resources = getResources();
        //獲取系統的配置
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        //將語言設定成簡體中文
        config.locale = Locale.CHINESE;
        resources.updateConfiguration(config, dm);


倒數第二行   Locale.  後面跟的什麼語言就是什麼語言   如果你新建了中文values-zh-rCN  這個會變成系統預設 換成  Locale.CHINESE   就會變成你一剛開始 系統自帶的strings.xml   換完之後執行一下    發現沒有換成自己設定的語言??? 為什麼呢  ------ 因為沒有重新整理頁面  - - 。

三,重新整理頁面 

上面的佈局檔案 裡面有個Button記得嗎?? 在Java程式碼裡面  設定點選事件 裡面程式碼如下
btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                overridePendingTransition(0,0);
            }
        });


跳轉動畫太難看了  , 我就取消了 變成閃一下的 ------  好了  現在執行是不是語言就換了呢  哈哈  那麼現在問題就來了~~~~~~不同語言對應的不同values資料夾應該怎麼命名呢? 這是個好問題 詳情看下一片部落格 88