Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial we will create an app that can support multiple language, In other words user can select his desired language to change whole app language in android.

This is an Simple Example on how do i change the app language programmatically android.

how to change app language android
DEMO

Step 1 − Create a new Android Project in Android Studio

Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. ( Name it as Change App language)

Step 2 – Create a new strings.xml with locale

In values directory, you need to create saperate string.xml(hi) or any other language

Here is how to create locale string with language

right click on values directory => New => Values Resource File

The below dialog will pop up in android studio

Here you need to select your locale languages that your app will support.

how to create locale string in android how to create locale string in android

After creating saperate strings.xml files for particular languages your string directory will look something like this.

strings xml to change app languages

Now in those strings.xml file add the translated strings

string.xml (hi)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ऐप भाषा बदलें</string>
    <string name="language">नमस्ते दुनिया</string>
</resources>

likewise you can do for different language that you want to add into your android applicaton.

Step 3 – Create a LocaleHelper Class

Now create new java file and name it as Localehelper and add the below code

This class will help you in getting and storing language user that previously selected below he close the application using SharedPreferences

package com.example.applanguagechange.Language;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.preference.PreferenceManager;

import java.util.Locale;

/**
 * Created by abdalla on 10/2/17.
 */

public class LocaleHelper {

    private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

    public static Context onAttach(Context context) {
        String lang = getPersistedData(context, Locale.getDefault().getLanguage());
        return setLocale(context, lang);
    }

    public static Context onAttach(Context context, String defaultLanguage) {
        String lang = getPersistedData(context, defaultLanguage);
        return setLocale(context, lang);
    }

    public static String getLanguage(Context context) {
        return getPersistedData(context, Locale.getDefault().getLanguage());
    }

    public static Context setLocale(Context context, String language) {
        persist(context, language);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResources(context, language);
        }

        return updateResourcesLegacy(context, language);
    }

    private static String getPersistedData(Context context, String defaultLanguage) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
    }

    private static void persist(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 static Context updateResources(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Configuration configuration = context.getResources().getConfiguration();
        configuration.setLocale(locale);
        configuration.setLayoutDirection(locale);

        return context.createConfigurationContext(configuration);
    }

    @SuppressWarnings("deprecation")
    private static Context updateResourcesLegacy(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Resources resources = context.getResources();

        Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLayoutDirection(locale);
        }

        resources.updateConfiguration(configuration, resources.getDisplayMetrics());

        return context;
    }
}

 

Step 4 –  UI Design

activity_main.xml 

Add the following code to res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    tools:context=".MainActivity"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <RelativeLayout
        android:layout_width="200dp"
        android:layout_height="40dp"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="3dp"
        android:layout_marginRight="3dp"
        android:background="@drawable/spinner_background"
        android:orientation="horizontal">

    

        <TextView
            android:id="@+id/dialog_language"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentBottom="true"
            android:layout_gravity="center"
            android:gravity="center"
            android:background="@android:color/transparent"
            android:dropDownVerticalOffset="35dp"
            android:popupBackground="@color/colorPrimary"
            android:textColor="@color/white"
            android:text="@string/selectedlanguage" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_gravity="center"
            android:layout_marginRight="10dp"
            android:src="@drawable/drop" />

    </RelativeLayout>

</LinearLayout>

@drawable/spinner_background.xml

create a new drawable resource file under drawable folder and add the below code.

This code is just to give background to above relativelayout

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/colorPrimary"
        />
    <corners android:radius="40dp" />
    <stroke
        android:width="1dp"
        android:color="#05AC21" />
</shape>

Step 5 –  Java Code to switch between string.xml to use

Main_Activity.java

package com.example.applanguagechange;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.applanguagechange.Language.LocaleHelper;

public class MainActivity extends AppCompatActivity {
    TextView language_dialog,text1;
    boolean lang_selected;
    Context context;
    Resources resources;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        language_dialog = (TextView)findViewById(R.id.dialog_language);
        text1=(TextView)findViewById(R.id.text1);

        language_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String[] Language = {"ENGLISH", "हिन्दी"};
                final int checkedItem;

                if(lang_selected)
                {
                    checkedItem=0;
                }else
                {
                    checkedItem=1;
                }

                final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Select a Language...")
                        .setSingleChoiceItems(Language, checkedItem, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(MainActivity.this,""+which,Toast.LENGTH_SHORT).show();
                                language_dialog.setText(Language[which]);
                                lang_selected= Language[which].equals("ENGLISH");
                             //if user select prefered language as English then 
                                if(Language[which].equals("ENGLISH"))
                                {
                                    context = LocaleHelper.setLocale(MainActivity.this, "en");
                                    resources = context.getResources();

                                    text1.setText(resources.getString(R.string.language));
                                }
                                //if user select prefered language as Hindi then 
                                if(Language[which].equals("हिन्दी"))
                                {
                                    context = LocaleHelper.setLocale(MainActivity.this, "hi");
                                    resources = context.getResources();

                                    text1.setText(resources.getString(R.string.language));
                                }
                            }
                        })
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();
            }

        });
    }
}

Here in above code we have  a TextView with OnClickEvent, Then user will click the TextView a AlertDialog will popup asking for  language selection, by using which user can change language of his application

When user Select language as Hindi the strings.xml (hi) will get loaded and all the text in the application will turn it language string that come from strings.xml (hi),

and If select language as English all language will come back to defaut string.xml

Conclusion

In this tutorial we learnt how to change whole app language in android programmatically using strings.xml locale.

LEAVE A REPLY

Please enter your comment!
Please enter your name here