Skip to main content

Multi language support

This post will help you yo learn how to make Multi language supported app in android.
Why Multi language?
In order to targeting global audience, it will be beneficial if you make your app localized.
While localizing, you should think about text, audio, currency, numbers and graphics depending upon the region or country. But in this tutorial language only covered.




Note:
Whenever you are making any android application, Always declare text you want to use in your application in strings.xml only.
<string name="hello">Hello World!</string>

How String Localization Works?
By default android considers English as primary language and loads the string resources from res >> values >> strings.xml. When you want to make Multilanguage supported app, you need to create a values folder by appending a Hyphen (-) and the ISO language code. For example for Hindi, values-hi named folder should be created and keep a strings.xml file in it with all the strings translated into Hindi language.

Lets see the sample:


Create a project and create a strings.xml folder for different languages like for Hindi (values-hi), Arabic(values-ar)


Following code will do the localization

Locale locale = new Locale(languageToLoad);
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        context.getResources().updateConfiguration(config,

                context.getResources().getDisplayMetrics());

String.xml
Open strings.xml from values directory.

Paste following strings into values >> strings.xml files. These are default English text.
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Language Setting</string>
    <string name="welcome">Welcome</string>
    <string name="select_language">Select Language</string>
    <string name="hindi">हिंदी</string>
    <string name="arabic">عربى</string>
    <string name="save">Save</string>
</resources>

Make More for each language
Now as we discussed earlier about localization mechanism, Create new folder under res folder named values-hi, values-ar

Hindi values-hi >> strings.xml

<resources>
    <string name="app_name">भाषा सेटिंग</string>
    <string name="welcome">स्वागत हे</string>
    <string name="select_language">भाषा चुनिए</string>
    <string name="hindi">हिंदी</string>
    <string name="arabic">عربى</string>
    <string name="save">बचाना</string>

</resources>

Similarly for other languages.
MainActivity.java
public class MainActivity extends AppCompatActivity {

    private TextView tvLabel;
    public static SharedPreferences sharePrefs;
    String selLanguage;
    public static MainActivity mainActivity;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /** Initialize SharedPreferences **/        sharePrefs = PreferenceManager
                .getDefaultSharedPreferences(MainActivity.this);
        setAppLanguage();
        mainActivity = this;
    }

    private void setAppLanguage() {
        if(sharePrefs.contains("LANGUAGE")){
            selLanguage = sharePrefs.getString("LANGUAGE","");
        }else{
            selLanguage = "en";
        }
        ComUtil.setLanguage(MainActivity.this, selLanguage);

        tvLabel = findViewById(R.id.id_set_lang);
        tvLabel.setText(getResources().getText(R.string.welcome));
    }

    @Override    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.        
getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will        
// automatically handle clicks on the Home/Up button, so long        
// as you specify a parent activity in AndroidManifest.xml.        
int id = item.getItemId();

        //noinspection SimplifiableIfStatement        
if (id == R.id.action_settings) {
            Intent intent = new Intent(MainActivity.this,Setting.class);
            startActivity(intent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/id_set_lang"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="21sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
Setting.java
public class Setting extends AppCompatActivity implements View.OnClickListener {

    private CheckBox chkEng, chkArb, chkHind;
    private Button btnSave;
    String selLanguage;

    public static SharedPreferences sharePrefs;
    SharedPreferences.Editor sharePrefs_Editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting);

        /** Initialize SharedPreferences **/
        sharePrefs = PreferenceManager
                .getDefaultSharedPreferences(Setting.this);
        sharePrefs_Editor = sharePrefs.edit();

        chkEng = findViewById(R.id.id_chk_eng);
        chkHind = findViewById(R.id.id_chk_hind);
        chkArb = findViewById(R.id.id_chk_arb);

        btnSave = findViewById(R.id.id_save);

        setAppLanguage();
        setCheckBox(selLanguage);

        /*init_onclick*/
        chkEng.setOnClickListener(this);
        chkHind.setOnClickListener(this);
        chkArb.setOnClickListener(this);
        btnSave.setOnClickListener(this);

    }

    private void setCheckBox(String xsetLan) {
        switch (xsetLan){
            case "en":
                chkEng.setChecked(true);
                chkHind.setChecked(false);
                chkArb.setChecked(false);
                break;
            case "hi":
                chkEng.setChecked(false);
                chkHind.setChecked(true);
                chkArb.setChecked(false);
                break;
            case "ar":
                chkEng.setChecked(false);
                chkHind.setChecked(false);
                chkArb.setChecked(true);
                break;
        }
    }

    private void setAppLanguage() {
        if(sharePrefs.contains("LANGUAGE")){
            selLanguage = sharePrefs.getString("LANGUAGE","");
        }else{
            selLanguage = "en";
        }
        ComUtil.setLanguage(Setting.this, selLanguage);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.id_chk_eng:
                chkHind.setChecked(false);
                chkArb.setChecked(false);
                break;
            case R.id.id_chk_hind:
                chkArb.setChecked(false);
                chkEng.setChecked(false);
                break;
            case R.id.id_chk_arb:
                chkHind.setChecked(false);
                chkEng.setChecked(false);
                break;
            case R.id.id_save:
                if (chkEng.isChecked()) {
                    selLanguage = "en";
                }
                if (chkHind.isChecked()) {
                    selLanguage = "hi";
                }
                if (chkArb.isChecked()) {
                    selLanguage = "ar";
                }

                sharePrefs_Editor.putString("LANGUAGE", selLanguage);
                sharePrefs_Editor.commit();
                MainActivity.mainActivity.finish();
                Intent intent = new Intent(Setting.this, MainActivity.class);
                startActivity(intent);
                finish();
                break;
        }
    }

    @Override
    protected void onResume() {
        setAppLanguage();
        super.onResume();
    }
}

setting.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:background="@color/colorGray_One"
    tools:context=".MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorWhite"
        android:layout_margin="10dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:orientation="vertical">
            <TextView
                android:id="@+id/id_lan_label"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="@color/colorBlack"
                android:text="@string/select_language"/>
            <LinearLayout
                android:layout_below="@+id/id_lan_label"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="10dp">
                <CheckBox
                    android:id="@+id/id_chk_eng"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:layout_gravity="center"
                    android:checked="true"
                    android:text="English"/>
                <CheckBox
                    android:id="@+id/id_chk_hind"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:layout_gravity="center"
                    android:text="@string/hindi"/>
                <CheckBox
                    android:id="@+id/id_chk_arb"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:layout_gravity="center"
                    android:text="@string/arabic"/>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_marginBottom="10dp"
        android:layout_alignParentBottom="true">
        <Button
            android:id="@+id/id_save"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:textColor="@color/colorWhite"
            android:text="@string/save"/>
    </LinearLayout>

</RelativeLayout>

ComUtil.java
public class ComUtil {

    public static void setLanguage(Context context, String languageToLoad) {
        Locale locale = new Locale(languageToLoad);
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        context.getResources().updateConfiguration(config,
                context.getResources().getDisplayMetrics());
    }
}
That's all for localization - Download sample here - MultiLanguage
_________________________________________________________________________________________
Happy Coding...

Comments

Popular posts from this blog

Spinner with Search on DropDown - Android Tutorial

If you have more values on Dropdown of Spinner its hard to select the last item by making a long scroll. To overcome this issue Android introduced a component called  AutoCompleteTextView Yes it is!!! Then why Spinner with Search? There may be some requirement even though gave much knowledge about it. There is a simple and good library that helps us to achieve this -  SearchableSpinner Gradle dependencies {     ...     implementation 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1' } Usage Now replace your Normal Android Spinner on XML with the following < com.toptoche.searchablespinnerlibrary.SearchableSpinner     android:id="@+id/id_city"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:background="@android:color/transparent"     android:padding="5dp" /> ______________________________________...

Get Phone Number from Contact List - Android Tutorial

When you create an application to send sms or an application to make calls, getting a destination number from the contacts list is a common task. In this Android tip, I am going to show the code to fetch a number from the contacts list. Now let me tell you how to achieve the goal. First, you need to create an Intent object for the PICK_ACTION action. To open the contacts list, the table that contains the contacts information must be specified as a parameter of the constructor of the Intent class. You can refer to the table using ContactsContract.Contacts.CONTENT_URI. Then call the startActivityForResult () method passing the Intent object and request code to open the contacts list. After a contact is selected from the contacts list, to get the result, you need to override the onActivityResult(int reqCode, int resultCode, Intent data) method of the activity. You can call the getData() method of the data parameter to get the table or uri that contains the selected contact. From the t...

Bluetooth Chat Application - Android Tutorial

In this tutorial, we will see about how to design an Android layout for chat application using Chat Bubbles  and the main part is chat via Bluetooth . Main objective of this post is to give an idea about how to allow two-way text chat over Bluetooth in android. Bubbles: Chat bubbles are background image that expands horizontally and vertically as required based on the message posted. Bubbles are Nine-patch Images. Image Nine-patch Image In creating Android chat bubbles, nine-patch image plays a crucial role.  Nine-patch image  is a bitmap which stretches to fit the content posted in the View where it is applied as a background. A NinePatch drawable is a standard PNG image that includes an extra 1-pixel-wide border. It must be saved with the extension  .9.png , and saved into the  res/drawable/  directory of your project. The border is used to define the stretchable and static areas of the image. You indicate a stretchable section ...