In-app switching language

Source: Internet
Author: User

Reprint please specify the source http://www.cnblogs.com/cnwutianhao/p/6746981.html

A few days ago, customer demand, add a function to the app, this feature is already very common on the market, that is, in-app switching language. What do you mean, English, Chinese, French, German, and Japanese? Language to switch freely.

(this case uses data-bingding mode, MA Ma no longer worry I findviewby not to ID, haha, open a joke)

First, the example diagram:

Code implementation:

Layout file (data-binding mode), very simple is two lines of text

<?XML version= "1.0" encoding= "Utf-8"?><Layoutxmlns:android= "Http://schemas.android.com/apk/res/android">    <RelativelayoutXmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Tools:context= "Com.tnnowu.android.switchlanguage.MainActivity">        <TextViewAndroid:id= "@+id/titletextview"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:layout_centerinparent= "true"Android:text= "@string/title"android:textsize= "30SP"Android:textstyle= "Bold" />        <TextViewAndroid:id= "@+id/desctextview"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_below= "@+id/titletextview"Android:layout_centerhorizontal= "true"Android:layout_margintop= "10DP"Android:text= "@string/desc"android:textsize= "20SP" />    </Relativelayout></Layout>

From the example we can see that there is a menu in the upper right corner

<?XML version= "1.0" encoding= "Utf-8"?><Menuxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Tools:context=". Mainactivity ">    <ItemAndroid:id= "@+id/language_english"android:orderincategory= "+"Android:title= "@string/menu_english" />    <ItemAndroid:id= "@+id/language_simplified_chinese"android:orderincategory= "+"Android:title= "@string/menu_simplified_chinese" />    <ItemAndroid:id= "@+id/language_turkish"android:orderincategory= "+"Android:title= "@string/menu_turkish" />    <ItemAndroid:id= "@+id/language_japanese"android:orderincategory= "+"Android:title= "@string/menu_japanese" /></Menu>

(since it is multi-lingual, so there will be n a strings)

, I have created 4 languages in this case.

OK, the layout of the menu is finished, the next step is to implement the menu function, remember to implement the menu on two sets of code, one Oncreateoptionsmenu, the other is onoptionsitemselected.

@Override  Public Boolean Oncreateoptionsmenu (Menu menu) {    getmenuinflater (). Inflate (R.menu.menu, menu);     return true ;}
@Override Public Booleanonoptionsitemselected (MenuItem item) {intID =Item.getitemid (); if(id = =r.id.language_english) {Updateviews ("EN"); } Else if(id = =R.id.language_simplified_chinese) {Updateviews ("EN"); } Else if(id = =r.id.language_turkish) {Updateviews ("TR"); } Else if(id = =R.id.language_japanese) {Updateviews ("Ja"); }    return Super. onoptionsitemselected (item);}

Here, we can see that we are customizing a updateviews () method, which is used to realize the change of the interface when switching prophecies.

Private void updateviews (String languagecode) {    = Localehelper.setlocale (this, languagecode);     = context.getresources ();    MBinding.titleTextView.setText (resources.getstring (R.string.title));    MBinding.descTextView.setText (resources.getstring (R.string.desc));    Settitle (resources.getstring (R.string.toolbar_title));}

Publication of a language-judging class Localehelper

 Public classLocalehelper {Private Static FinalString selected_language = "Locale.Helper.Selected.Language";  Public StaticContext Onattach (context context) {String lang=getpersisteddata (context, Locale.getdefault (). GetLanguage ()); returnSetLocale (context, Lang); }     Public StaticContext Onattach (context context, string defaultlanguage) {string Lang=getpersisteddata (context, defaultlanguage); returnSetLocale (context, Lang); }     Public StaticString GetLanguage (context context) {returngetpersisteddata (context, Locale.getdefault (). GetLanguage ()); }     Public StaticContext SetLocale (context context, String language) {persist (context, language); if(Build.VERSION.SDK_INT >=Build.version_codes. N) {returnupdateresources (context, language); }        returnupdateresourceslegacy (context, language); }    Private Staticstring Getpersisteddata (context context, String DefaultLanguage) {sharedpreferences preferences=preferencemanager.getdefaultsharedpreferences (context); returnpreferences.getstring (Selected_language, defaultlanguage); }    Private Static voidpersist (Context context, String language) {sharedpreferences preferences=preferencemanager.getdefaultsharedpreferences (context); Sharedpreferences.editor Editor=Preferences.edit ();        Editor.putstring (Selected_language, LANGUAGE);    Editor.apply (); } @TargetApi (Build.version_codes. N)Private StaticContext Updateresources (context context, String language) {locale locale=NewLocale (language);        Locale.setdefault (locale); Configuration Configuration=context.getresources (). GetConfiguration ();        Configuration.setlocale (locale); returncontext.createconfigurationcontext (configuration); } @SuppressWarnings ("Deprecation")    Private StaticContext Updateresourceslegacy (context context, String language) {locale locale=NewLocale (language);        Locale.setdefault (locale); Resources Resources=context.getresources (); Configuration Configuration=resources.getconfiguration (); Configuration.locale=locale;        Resources.updateconfiguration (Configuration, Resources.getdisplaymetrics ()); returncontext; }}

The last thing to do is to customize a application class that sets the default language for the app (of course, to apply this application to manifest)

 Public class extends Application {    @Override    protectedvoid  attachbasecontext (Context base) {         Super. Attachbasecontext (Localehelper.onattach (Base, "en"));}    }

This case implementation of the app language switch code is small, easy to understand, no garbage code.

Sample code: In-app switching language

Follow me on Sina Weibo, please look for the Yellow v certification, get the latest Android development information.

Focus on technology critics, learn about technology, innovation, education and maximizing human intelligence and imagination!

In-app switching language

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.