Open In App

Android – Per App Language Preference with Example

Last Updated : 31 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Many android applications add localization within their application to provide multi-lingual support within their android application. While implementing this feature the android application will take the device language to set the language for the android application and we cannot change the language dynamically from the application. In this article, we will be creating a simple application in which users will be dynamically able to switch the language from the application when the app is running. We will be using Android 13 Language Preference API to implement this. A sample video is given below to get an idea about what we are going to do in this article.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Step 2: Create a folder values-hi to store the custom messages

Create a folder values-hi by following the following steps. The -hi extension defines that if the device’s preference is set to Hindi (hi), the context within the application would be set according to the data present in the values-hi folder. Click on Android and select the Project option:

 

Now expand the folder until you find the res (Resources) folder, right-click on it, select new, and click Android Resource Directory.

 

Set the directory name as values-hi

 

The values-hi folder is now created

 

Step 3: Create a strings.xml file

Create a strings.xml file in this folder, that shall contain a custom message. Entities of this file should match the entities of the default strings.xml file. Now add a Values Resource File in the values-hi folder.

 

Give it a name, and strings, and it creates a .XML file

 

strings.xml file is created in the values-hi folder

 

Go back to the Android view and check if the newly created file is present.

 

The file is available under the values/strings folder

Step 4: Add the custom message values to string.xml (regular) and string.xml (hi)

Add a custom message to the pre-existing as well as the newly created strings.xml file. The entities of both file must be the same, the context may differ. Below is the code for the strings.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">GFG</string>
    <string name="language">Hindi</string>
    <string name="heading">गीक्स फॉर गीक्स में आपका स्वागत है</string>
    <string name="sub_heading">सभी को नमस्कार
</string>
</resources>


Similarly, create string.xml for other languages. Below is the code for different languages. Assamese Language.

XML




<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">GFG</string>
    <string name="language">Assamese</string>
    <string name="sub_heading">"নমস্কাৰ সকলোকে "</string>
    <string name="heading">"Geeks for Geeks লৈ আপোনাক স্বাগতম "</string>
</resources>


Kannada Language.

XML




<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">GFG</string>
    <string name="language">Kannada</string>
    <string name="sub_heading">"ಎಲ್ಲರಿಗೂ ನಮಸ್ಕಾರ "</string>
    <string name="heading">"ಗೀಕ್ಸ್‌ಗಾಗಿ ಗೀಕ್ಸ್‌ಗೆ ಸುಸ್ವಾಗತ "</string>
</resources>


Nepali Language

XML




<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">GFG</string>
    <string name="language">Nepali</string>
    <string name="heading">"Geeks को लागी Geeks मा स्वागत छ "</string>
    <string name="sub_heading">"सबैलाई नमस्कार "</string>
</resources>


Step 5: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <!-- creating text view to display heading -->
    <TextView
        android:id="@+id/idTVHeading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="10dp"
        android:padding="5dp"
        android:text="@string/heading"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="25sp"
        android:textStyle="bold" />
  
    <!-- creating text view to display sub heading -->
    <TextView
        android:id="@+id/idTVSubHeading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idTVHeading"
        android:gravity="center"
        android:text="@string/sub_heading"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="20sp" />
  
    <!-- creating text view to display current language -->
    <TextView
        android:id="@+id/idTVCurrentLanguage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idTVSubHeading"
        android:gravity="center"
        android:text="Current Language"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="20sp" />
  
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idTVCurrentLanguage"
        android:layout_margin="5dp"
        android:orientation="horizontal"
        android:padding="3dp"
        android:weightSum="2">
  
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="4dp"
            android:layout_weight="1"
            android:orientation="vertical">
  
            <!-- creating buttons to switch between languages -->
            <Button
                android:id="@+id/idBtnHindi"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:backgroundTint="@color/button_color"
                android:text="Hindi"
                android:textAllCaps="false"
                android:textColor="@color/white" />
  
            <Button
                android:id="@+id/idBtnKannada"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:backgroundTint="@color/button_color"
                android:text="Kannada"
                android:textAllCaps="false"
                android:textColor="@color/white" />
  
        </LinearLayout>
  
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="4dp"
            android:layout_weight="1"
            android:orientation="vertical">
  
            <!-- creating buttons to switch between languages -->
            <Button
                android:id="@+id/idBtnNepali"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:backgroundTint="@color/button_color"
                android:text="Nepali"
                android:textAllCaps="false"
                android:textColor="@color/white" />
  
            <Button
                android:id="@+id/idBtnAssamese"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:backgroundTint="@color/button_color"
                android:text="Assamese"
                android:textAllCaps="false"
                android:textColor="@color/white" />
  
        </LinearLayout>
        
    </LinearLayout>
  
</RelativeLayout>


Step 6: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




package com.example.gptapp
  
import android.R.attr
import android.annotation.SuppressLint
import android.app.LocaleManager
import android.app.StatusBarManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.drawable.Icon
import android.net.Uri
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Bundle
import android.os.LocaleList
import android.provider.MediaStore
import android.util.Log
import android.view.inputmethod.EditorInfo
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.android.volley.RequestQueue
import com.android.volley.Response
import com.android.volley.RetryPolicy
import com.android.volley.VolleyError
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.textfield.TextInputEditText
import com.squareup.picasso.Picasso
import org.json.JSONObject
import java.util.*
import java.util.jar.Manifest
  
class MainActivity : AppCompatActivity() {
  
    // creating variables on below line.
    private var localeManager: LocaleManager? = null
    lateinit var headingTV: TextView
    lateinit var subHeadingTV: TextView
    lateinit var currentLngTV: TextView
    lateinit var hindiBtn: Button
    lateinit var kannadaBtn: Button
    lateinit var nepaliBtn: Button
    lateinit var assameseBtn: Button
  
    @RequiresApi(Build.VERSION_CODES.N)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
          
          // initializing local manager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            localeManager = getSystemService(Context.LOCALE_SERVICE) as LocaleManager
        }
  
        // initializing variables on below line.
        headingTV = findViewById(R.id.idTVHeading)
        currentLngTV = findViewById(R.id.idTVCurrentLanguage)
        subHeadingTV = findViewById(R.id.idTVSubHeading)
        hindiBtn = findViewById(R.id.idBtnHindi)
        nepaliBtn = findViewById(R.id.idBtnNepali)
        kannadaBtn = findViewById(R.id.idBtnKannada)
        assameseBtn = findViewById(R.id.idBtnAssamese)
  
        // adding click listener for our button.
        hindiBtn.setOnClickListener {
            // setting locale as hindi on below line.
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                localeManager?.applicationLocales = LocaleList(Locale.forLanguageTag("hi"))
            }
        }
  
        // adding click listener for our button.
        nepaliBtn.setOnClickListener {
            // setting locale as nepali on below line.
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                localeManager?.applicationLocales = LocaleList(Locale.forLanguageTag("ne"))
            }
        }
          
        // adding click listener for our button.
        kannadaBtn.setOnClickListener {
            // setting locale as kannada on below line.
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                localeManager?.applicationLocales = LocaleList(Locale.forLanguageTag("kn"))
            }
        }
  
        // adding click listener for our button.
        assameseBtn.setOnClickListener {
            // setting locale as assamese on below line.
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                localeManager?.applicationLocales = LocaleList(Locale.forLanguageTag("as"))
            }
        }
    }
  
    override fun onResume() {
        super.onResume()
  
        // setting current language on below line 
          // and setting it to text view.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            val language = when (localeManager?.applicationLocales?.toLanguageTags()) {
                "en" -> "English"
                "as" -> "Assamese"
                "kn" -> "Kannada"
                "ne" -> "Nepali"
                "hi" -> "Hindi"
                else -> "Not Set"
            }
            currentLngTV.text = "Current In-App Language: $language"
        }
  
    }
}


Now run your application to see the output of it.

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads