1. 程式人生 > >Android(國際化)多語言的實現和切換

Android(國際化)多語言的實現和切換

Android 的多語言設定在開發中時有用到,實現也不復雜,主要包括三個方面


不同語言的資源的實現,即string.xml的實現
利用Locale改變系統的語言設定

 

 

 


首先需要將不同語言版本的資源配置好

 

 

新建values資料夾,不同國家的資料夾名字不一樣 
 
 
 

 

根據需要選擇建立對應語言的資原始檔夾,資料夾名稱系統會自動生成 
 

 

 


然後在對應的資原始檔夾下面新建string.xml檔案,不同語言的字串資源的名稱要一樣,如下面的中文和英文:

 


//英文資源
<resources>
    <string name="app_language">language</string>
</resources>

//中文資源
<resources>
    <string name="app_language">語言</string>
</resources>

 

通過以上步驟,資原始檔已經準備好,接下去就是改變系統的語言環境,這就需要用到Locale


生成新的Locale物件

 


public Locale(String language, String country) {
        this(language, country, "");
}

//例如,生成English,不限地區的Locale物件
new Locale("en", ")


更改系統的語言設定

 


Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = newLocale;
resources.updateConfiguration(configuration, resources.getDisplayMetrics());//更新配置1234


需要注意的是,更改語言配置需要在MainActivity的setContentView()之前設定才會起作用

 


public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initLocaleLanguage();
        setContentView(R.layout.activity_main);
    }
}

private void initLocaleLanguage() {
    Resources resources = context.getResources();
    Configuration configuration = resources.getConfiguration();
    configuration.locale = newLocale;
    resources.updateConfiguration(configuration, resources.getDisplayMetrics());//更新配置
}

 

一般的更改語言的選項都在App的設定裡面,改變系統的Locale以後並不會馬上生效,需要重啟App以後才會有效。如果要及時生效,就需要重啟MainActivity,方法如下:

 

//重啟MainActivity
Intent intent = new Intent(SettingActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);1234

通過以上步驟,多語言的實現基本就Ok了,需要什麼語言進行對應的設定即可,都是一樣的思路。
--------------------- 
作者:xxq2dream 
來源:CSDN 
原文:https://blog.csdn.net/myth13141314/article/details/62037194 
版權宣告:本文為博主原創文章,轉載請附上博文連結!