Android implements the built-in language switching function of applications
1、 Demand
Sometimes the application needs to switch the language internally without affecting the system language. For example, the application is now Chinese, and the system language is also Chinese. After I switch the application to English, the system language is still Chinese, and the system language will not be changed after switching. In addition, the systems of some machines have been modified and simplified, For example, the system languages of some domestic machines have been simplified, leaving Chinese and English. Alipay, WeChat and Top Story have functions such as language switching in application settings.
2、 Realization effect
Let's see the effect first.
3、 Realize
(1) Add resource folders and files in multiple languages
I default to English and add a Russian (Google Translated) and Chinese.
values/strings.xml
values-ru/strings.xml
values-zh/strings.xml
(2) Layout file activity_ main.xml
The text of the default title bar will not be changed after switching the language. Just replace it with toobar.
styles.xml
After setting the language, you need to restart the activity. The startup will have an effect. Use windowsdisablepreview to mask it.
main_ menu.xml
(3) Localeutils
Locale tool class. Here I use SharedPreferences to save the set locale. Locale implements serializable.
(4) Activity
There is only one activity here, so it's good to restart the current activity when switching. There are other activities in the stack, so you can deal with them yourself.
(5) Application
When the application oncreate is updated, the previously set language should be kept unchanged when the system language is changed.
Source address: Android application built-in language switching
The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.