1、所謂的多語言的實(shí)現(xiàn),是指同一個(gè)應(yīng)用界面能支持多種語言的顯示,供不同語言的人使用。也就是我們應(yīng)用內(nèi)顯示的字符串都要有不同語言的多個(gè)備份,共系統(tǒng)根據(jù)需要調(diào)用。
要實(shí)現(xiàn)這個(gè)功能,首先的一點(diǎn)是不能把要顯示的字符串寫死在代碼里,而是應(yīng)該寫到對(duì)應(yīng)的配置文件中,也就是res目錄下的strings.xml中。
2、根據(jù)需求為每種要支持的語言創(chuàng)建一份對(duì)應(yīng)的strings.xml。
1)
2) 在打開的對(duì)話框中填寫文件名,選擇locale,并選擇要支持的語言和地區(qū)。
這樣,應(yīng)用中顯示的每一個(gè)字符串在上述方法得到的各個(gè)strings.xml文件中都需要有一個(gè)備份(當(dāng)然,語言的內(nèi)容要更改為對(duì)應(yīng)語言)。
3、至此,對(duì)多語言的支持就完成了。只要設(shè)備設(shè)定的語言在我們支持的語言當(dāng)中,系統(tǒng)就會(huì)自動(dòng)調(diào)用對(duì)應(yīng)的strings.xml中的內(nèi)容進(jìn)行顯示。
圖1
圖2
如上圖,圖1是應(yīng)用的登錄界面,點(diǎn)擊右上角的“語言”,就可以跳轉(zhuǎn)到圖2語言切換頁面。
在圖2中選擇一種語言,應(yīng)用就會(huì)顯示為對(duì)應(yīng)語言的版本。
切換語言的關(guān)鍵代碼如下:
1、
Locale locale = new Locale("zh");Locale.setDefault(locale);Configuration config = new Configuration();config.locale = locale;getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
Intent intent = new Intent();intent.setClass(Language_set.this, LoginActivity.class);intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity,all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.startActivity(intent);
上面那段灰色的英文解釋的意思是:設(shè)置為該flag后,如果要啟動(dòng)的activity在棧中已經(jīng)存在,那么不會(huì)創(chuàng)建新的activity而是將棧中該activity上方的所有activity出棧。這樣做的目的是使所有的activity都顯示為當(dāng)前設(shè)定的語言。
當(dāng)然至此只能是這次使用過程中語言設(shè)定成功。如果想應(yīng)用下一次啟動(dòng)時(shí)還使用當(dāng)前設(shè)置的語言類型就要將當(dāng)前語言設(shè)置保存起來,在下次打開應(yīng)用時(shí)進(jìn)行讀取。
保存很簡單就不寫了。
在啟動(dòng)activity中進(jìn)行讀取并設(shè)置:
String filename="LoginDataStore";String field="Language";String lang=ForDataStoreAndRead.getSharePreString(FinishiActivity.this,filename,field);if (lang.equals("0")) lang="zh";switchLanguage(lang);
protected void switchLanguage(String language) {//shezhiyingyong yuyan de leixing Resources resources = getResources(); Configuration config = resources.getConfiguration(); DisplayMetrics dm = resources.getDisplayMetrics(); switch (language) { case "en": config.locale = Locale.ENGLISH; resources.updateConfiguration(config, dm); break; case "zh": config.locale = Locale.SIMPLIFIED_CHINESE; resources.updateConfiguration(config, dm); break; default: config.locale = Locale.SIMPLIFIED_CHINESE; resources.updateConfiguration(config, dm); break; }}
聯(lián)系客服