1. 程式人生 > >android根據當前系統設定語言在app實現中英文切換

android根據當前系統設定語言在app實現中英文切換

今天介紹下安卓開發下面,如何實現中英文相互切換,

一,需要在res下新建資料夾,大陸中文為values-zh-rCN,英文values-en-rUS,更多可以參考http://my.oschina.net/quttap/blog/204499,直接用values-zh,values-en也可以,可以自己查詢,然後其下新建strings.xml,(注:android預設訪問values下strings.xml,當設定其它語言找不到對應資料夾時,將轉而訪問values下的strings.xml)

二,通過getResources().getConfiguration().locale.getLanguage()來獲取當前應用語言,中文為zh,英文為en,更多可以參考http://blog.sina.com.cn/s/blog_7981f91f01012wm7.html

三,在androidmianfest.xml中配置下屬性android:configChanges="locale",就是利用系統類設定語言,附主要程式碼,

@Override             public void onClick(View v) {                 // TODO Auto-generated method stub                 String sta=getResources().getConfiguration().locale.getLanguage();                 shiftLanguage(sta);             }

//shift language     public void shiftLanguage(String sta){         if(sta.equals("zh")){         Locale.setDefault(Locale.ENGLISH);          Configuration config = getBaseContext().getResources().getConfiguration();                 config.locale = Locale.ENGLISH;                  getBaseContext().getResources().updateConfiguration(config                     , getBaseContext().getResources().getDisplayMetrics());                 refreshSelf();         }else{             Locale.setDefault(Locale.CHINESE);              Configuration config = getBaseContext().getResources().getConfiguration();             config.locale = Locale.CHINESE;              getBaseContext().getResources().updateConfiguration(config                 , getBaseContext().getResources().getDisplayMetrics());             refreshSelf();         }     }     //refresh self     public void refreshSelf(){         Intent intent=new Intent(this,MainActivity.class);         intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);         startActivity(intent);     }