ADVERTISEMENT

How to change language in android programmatically


You might have come across apps which give you chances to change language during application run-time. Normally developers do this to allow app flexibility and increase app interactivity. Today our main focus is on how to change language in android programmatically. In this tutorial, am going to use 4 languages only i.e. English, Chinese, Hindi and Swahili. For this tutorial, I will be using google translate. We we will also save users choice so that we will remember it next time user opens the app. Okay let’s jump into development.

1. Create New Project

I have created new android project called Android Changing Language. Now, feel free to name your project anything that will make you comfortable. Well, our main focus here will be on strings.xml and Java, MainActivity.

See Images and video at the bottom of the page.

2. Create Overflow Menu

User will be selecting preferred language from overflow menu, so go a head and create menu_main.xml and add this code:

<?xml version="1.0" encoding="utf-8"?>


<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item 
          android:id="@+id/action_english" 
          android:title="English" />

    <item 
          android:id="@+id/action_chinese"
          android:title="Chinese" />

    <item
          android:id="@+id/action_hindi"
          android:title="Hindi" />


    <item
          android:id="@+id/action_swahili" 
          android:title="Swahili" />
</menu>


3. Creating Required Strings Resources files



We are going to use four languages, luckily, English is default, so we have been provided with that already. To create string resources for other languages is a bit tricky. First thing that you must know is language code. Well, you don’t have to worry about language codes as android studio has provided that. Shortly, am going to show you how to get language code in android studio. Let’s create string resources for Chinese, for the rest languages follow the same steps.

How to create string resources for a given language code:
Right click on the values resources directory found under res > values, create values resources file, name it strings. Then on the same screen, select Locale and click on the button labeled “>>” as shown in the image below. Now after clicking “>>”, you will be presented with language codes, along with countries. You can search for language that you want to translate.

Make sure all your string resources files are named strings.xml. Do that for other languages. That means you will create 4 string resource files, with different language code all named strings.xml. Now let’s have a look at strings.xml files that we have created.

English (Language code is: “en”)

<resources>
    <string name="app_name">Android Changing Language</string>

    <string name="display_text">
        I love software development and general programming
    </string>
</resources>

Chinese (Language code is: “zh”)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="display_text">
        我喜欢软件开发和一般编程
    </string>
</resources>

Hindi (Language code is: “hi”)

<?xml version="1.0" encoding="utf-8"?>
<resources>
     <string name="display_text">
        मुझे सॉफ्टवेयर विकास और सामान्य प्रोग्रामिंग पसंद है I
    </string>
</resources>

Swahili (Language code is: “sw”)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="display_text">
        Ninapenda maendeleo ya utaalamu wa kompyuta na programu kwa jumla
    </string>
</resources>

Our main focus is on display_text resource value.

4. R.layout.activity_main

This is how our layout for the main activity looks like:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="hacksmile.com.androidchanginglanguage.MainActivity">

    <TextView
        android:id="@+id/language_indicator"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="15dp"
        android:text="English"
        android:textColor="#000"
        android:textSize="25sp" />

    <TextView
        android:id="@+id/display_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:padding="15dp"
        android:text="@string/display_text"
        android:textColor="#000"
        android:textSize="25sp" />
<!-- text view above will display text in selected language, refer to the all string.xml files to see display_text  -->


</LinearLayout>

Language indicator TextView will be used to indicate selected language and Display Text TextView will be used to display text in selected language.



5. MainActivity.java

This is our main MainActivity.java

package hacksmile.com.androidchanginglanguage;

import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    
    // these two variables will be used by SharedPreferences
    private static final String FILE_NAME = "file_lang"; // preference file name
    private static final String KEY_LANG = "key_lang"; // preference key

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // please load language after super and before setContentView
        loadLanguage();
        setContentView(R.layout.activity_main);


        TextView indicatorText = (TextView) findViewById(R.id.language_indicator);

        if (getLangCode().contentEquals("en")) {
            indicatorText.setText("English");
        } else if (getLangCode().contentEquals("zh")) {
            indicatorText.setText("Chinese");
        } else if (getLangCode().contentEquals("hi")) {
            indicatorText.setText("Hindi");
        } else if (getLangCode().contentEquals("sw")) {
            // default
            indicatorText.setText("Swahili");
        }
    }

    private void saveLanguage(String lang) {


        // we can use this method to save language
        SharedPreferences preferences = getSharedPreferences(FILE_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(KEY_LANG, lang);
        editor.apply();
        // we have saved
        // recreate activity after saving to load the new language, this is the same
        // as refreshing activity to load new language

        recreate();

    }

    private void loadLanguage() {
        // we can use this method to load language,
        // this method should be called before setContentView() method of the onCreate method

        Locale locale = new Locale(getLangCode());
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        getResources().updateConfiguration(config, getResources().getDisplayMetrics());
    }

    private String getLangCode() {
        SharedPreferences preferences = getSharedPreferences(FILE_NAME, MODE_PRIVATE);
        String langCode = preferences.getString(KEY_LANG, "en");
        // save english 'en' as the default language
        return langCode;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_english:
                saveLanguage("en");
                break;

            case R.id.action_chinese:
                saveLanguage("zh");
                break;

            case R.id.action_hindi:
                saveLanguage("hi");
                break;

            case R.id.action_swahili:
                saveLanguage("sw");
                break;
        }
        return true;
    }
}

Be careful when loading language. Always load language right before setContentView. Everything else is self explanatory. Please read carefully to grasp all the concepts.

Hack Smile Android change language programmatically - EnglishHack Smile Android change language programmatically - SwahiliHack Smile Android change language programmatically - HindiHack Smile Android change language programmatically - Chinese

In case of assistance or questions, please ask in the commenting system below. I will attend to each and every comment. Thanks



AdBlock Detected!
This site depends on revenue from ad impressions to survive. If you find this site valuable, please consider disabling your ad blocker or pausing adblock for this website.