(原創)獲取系統語言方式及動態全局切換語言方式
1.獲取當前系統語言
Locale locale = Constants.context.getResources().getConfiguration().locale;
String language = locale.getLanguage();//“zh”爲中文,“en”爲英文...
2.動態切換全局語言,注意:一般情況下都是需要關閉當前app再重新啓動纔不會崩潰,但是可以在清單文件配置後就可以實現不關閉情況下正常運行
(1).AndroidManifest.xml清單文件配置語言不跟隨系統變化(避免用戶手動到系統設置裏面切換語言導致當前app崩潰的情況)
//其中android:configChanges="locale|layoutDirection|navigation|fontScale"作用就是不跟隨系統語言變化</span>
<activity
android:name=".MainActivity"
android:configChanges="locale|layoutDirection|navigation|fontScale"
android:launchMode="singleTask"
android:screenOrientation="portrait"/>
(2).當前app動態全局切換語言:注意這只是切換自身app當前全局語言而非手機系統的語言
Configuration config = UIUtils.getResources().getConfiguration();
if (”添加條件“) {//切換中文
config.locale = Locale.CHINA;
} else {//切換英文
config.locale = Locale.ENGLISH;
}
//更新配置環境
getContext().getResources().updateConfiguration(config, null);
注意:對於當前界面在不關閉的情況下只能在自身通過動態的重新setText()方式切換,其他跳轉獲取已經關閉了的界面就不用動態setText()。
3.最後也就是需要添加中英文res文件夾---裏面存放需要切換的string字符串,注意中英文name="名稱"裏面的"名稱"要中英文一致,切換語言系統會自動尋找(沒有該文件夾自行創建)
values/string.xml爲默認顯示文本
values-en/string.xml爲切換英文顯示文本
values-zh/string.xml爲切換中文顯示文本