Android language switching -- Taking English as an example

Recently, I am working on an app for memorizing words as my graduation project. I want to design a function to switch the language from English in the app, and record the effect and steps of this implementation.

Realization effect

Chinese mode


English mode


PS: please don't make complaints about my garbage.

Implementation principle

In Android, there will be different response events for different ConfigChanges. The change of mobile phone language status will cause the use of the corresponding res / values directory. For example, for the Chinese mode, the default folder is used:

For English, we use values_ The xml file in the folder of en.

The folder name corresponding to the language can directly create the corresponding resource dictionary through Android studio:

Then choose the corresponding language. Take English as an example:

The same is true for other language folders.

Then translate the corresponding string in the String.xml file under the corresponding language folder.

For system language level switching, App will automatically respond and switch to the corresponding language. If the corresponding language has no relevant folder, the default language folder will be used. If there is, the corresponding language folder will be used.

For the language switching within the app, you need to manually switch the corresponding ConfigChanges event through the code.

Implementation steps

1. Create the relevant value folder and string.xml file

2. Select the appropriate translation in the corresponding string file

string file under values folder (default):

<resources>
    <string name="app_name">Happy back</string>
    <string name="dialog_title">Tips</string>
    <string name="dialog_main_exit_text">No more words today?</string>
    <string name="dialog_main_exit_yes">sign out</string>
    <string name="dialog_main_exit_no">Recite again</string>

    <string name="day">day</string>
    <string name="words">Words</string>

    <string name="search">search</string>
    <string name="set_goals">  &#160;Set goals&#160;  </string>
    <string name="leaning_data">&#160;Learning data&#160;  </string>
    <string name="CET_4_book_name">Level 4 vocabulary book</string>
    <string name="today_target">everyday</string>
    <string name="today_maintain">surplus</string>
    <string name="learned_word">Learned words</string>
    <string name="plan_today">Plan today</string>
    <string name="need_learning">Need new learning</string>
    <string name="need_review">Need review</string>
    <string name="beging_learning">Start learning!</string>

    <string name="function_expore">Functional exploration</string>

    <string name="days_of_persistence">Days of persistence</string>
    <string name="accumulate_words">Accumulate words</string>
    <string name="clock_in_calendar">Punch in calendar</string>
    <string name="data_analysis">Data analysis</string>
    <string name="words_list">Word list</string>
    <string name="collected_word">Favorites</string>
    <string name="night_mode">Night mode</string>
    <string name="night_mode_tips">It's more eye-friendly to turn on the night mode at night</string>
    <string name="notification_bar">Notice bar word</string>
    <string name="notification_bar_tips">The notice bar displays words to help you learn better</string>
    <string name="language_setting">English model</string>
    <string name="language_setting_tips">Open the English mode and feel the English atmosphere</string>
    <string name="cloud_bridge">Cloud</string>
    <string name="cloud_bridge_tips">Data cloud backup/recovery</string>
    <string name="about">about</string>
    <string name="about_tips">About me/Contact me</string>
    
    <string name="know">know</string>
    <string name="vague">vague</string>
    <string name="dont_know">incognizance</string>
    <string name="ES">example sentence:</string>
</resources>

values_ string file in en folder (English):

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">LeBei</string>
    <string name="dialog_title">Tips</string>
    <string name="dialog_main_exit_text">No More Words Today?</string>
    <string name="dialog_main_exit_yes">Yes</string>
    <string name="dialog_main_exit_no">No</string>

    <string name="day">Days</string>
    <string name="words">Words</string>

    <string name="search">Searching</string>
    <string name="set_goals"> Set </string>
    <string name="leaning_data"> Learning Data </string>
    <string name="CET_4_book_name">CET-4</string>
    <string name="today_target">Every day</string>
    <string name="today_maintain">Surplus</string>
    <string name="learned_word">Hava Learned Words</string>
    <string name="plan_today">Todays Plan</string>
    <string name="need_learning">Need To Learn</string>
    <string name="need_review">Need To Review</string>
    <string name="beging_learning">Start Learning!</string>

    <string name="function_expore">Function Expore</string>

    <string name="days_of_persistence">Persistent Days</string>
    <string name="accumulate_words">Accumumlate Words</string>
    <string name="clock_in_calendar">Calendar</string>
    <string name="data_analysis">Analysis</string>
    <string name="words_list">Words List</string>
    <string name="collected_word">Stared Word</string>
    <string name="night_mode">Night Mode</string>
    <string name="night_mode_tips">More Eye-Friendly To Turn On The Night Mode At Night</string>
    <string name="notification_bar">Notification Words</string>
    <string name="notification_bar_tips">Open Notification Bar Word</string>
    <string name="language_setting">Chinese Mode</string>
    <string name="language_setting_tips">Switch Chinese Mode</string>
    <string name="cloud_bridge">Cloud Bridge</string>
    <string name="cloud_bridge_tips">Data Cloud Backup / Recovery</string>
    <string name="about">About</string>
    <string name="about_tips">About Me / Contact Me</string>

    <string name="know">Know</string>
    <string name="vague">Vague</string>
    <string name="dont_know">Don`t Know</string>
    <string name="ES">ES:</string>

</resources>

3. Use this string field in the corresponding view

Example:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:background="@color/colorBgLittleGrey"
    tools:context=".fragment.Fragment_function">
    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/textView6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginLeft="16dp"
        android:text="@string/function_expore"			//Here to use!!!!!
        android:textColor="@color/colorTextBlackNomal"
        android:textSize="@dimen/appbar_text_size"
        android:textStyle="bold"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <GridView
        android:id="@+id/function_grid_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:horizontalSpacing="16dp"
        android:numColumns="2"
        android:verticalSpacing="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView6" />
</androidx.constraintlayout.widget.ConstraintLayout>

To adapt to the mobile phone language switching, go to this step.
The following steps are also required for active modification within the APP.

4. Modify the Locale attribute corresponding to the resource file

Add the relevant code in the corresponding position of the language to be modified:

        switchToEnglish.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            // Get res resource object
            Resources resources = getActivity().getResources();
            // Obtain screen parameters, which are mainly used for the following switching
            DisplayMetrics metrics = resources.getDisplayMetrics();
            // Get configuration object
            Configuration config = resources.getConfiguration();
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    config.locale = Locale.ENGLISH;
                    locale = config.locale;
                    Toast.makeText(getContext(), "Switch to English mode!", Toast.LENGTH_SHORT).show();

                } else {
                    config.locale = Locale.CHINESE;
                    Toast.makeText(getContext(), "Switch to Chinese mode!", Toast.LENGTH_SHORT).show();
                }
                if (locale == Locale.ENGLISH) {
                    updateActivity("English");
                } else {
                    updateActivity("Chinese");
                }
            }
        });

The main thing to do in the above code is to switch the relevant properties of config.locale. See its source code for details.

5. Restart Activity

The relevant properties will not be reloaded until the Activity is restarted after modification. Therefore, the second step we need to do is to save the current properties and restart the Activity.

The detailed code is the updateActivity method:

    public void updateActivity(String language) {
        //Saves the currently selected language in the local SP
        SharedPreferencesUtils.setParem(getContext(), "languege", language);
        Locale local = this.locale;
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = local;
        res.updateConfiguration(conf, dm);
		//After setting the selected language, you need to clear all activities in the task stack and open the home page to ensure that the next page is the currently selected language
        Intent intent = new Intent(getActivity(), MainActivity.class);
        //Clear the task stack and ensure that the currently opened activit y is the top of the foreground task stack
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        getActivity().finish();
    }
}

6. Set the properties for recovering SP storage after restart

Here I refer to the online code and do it in the custom Application:

public class MyApplication extends Application {
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        setCurrLanguageMode();
    }

    //Set the language mode of the current APP
    private void setCurrLanguageMode() {
        String language = (String) SharedPreferencesUtils.getParem(this, "languege", "");
        Locale local = LanguageUtils.getLocale(language);
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = local;
        res.updateConfiguration(conf, dm);
    }

    public void init() {
        //LitePal.initialize(this);
    }
}

Final effect drawing

end.

Reference article:
https://www.jianshu.com/p/ef749f54faba Insert picture description here

Keywords: Android http

Added by texerasmo on Sat, 27 Nov 2021 05:38:19 +0200