Android - App preferred language

When distributing an app overseas, it is essential to adapt the app to multiple languages. Starting from Android 13, the application preferred language function has been added, that is, users can choose different languages ​​for each application. This article briefly introduces how to integrate the preferred language API of the application.

Use preferred language in system settings

Create configuration file

Create locale_config.xml

Create a file in the res/xml directory locale_config.xml, as follows:

<locale-config xmlns:android="http://schemas.android.com/apk/res/android">
    <locale android:name="zh" />
    <locale android:name="en" />
    <locale android:name="ru" />
    <locale android:name="ko" />
    <locale android:name="ja" />
</locale-config>

Here is a simple demonstration in several languages, and refer to official documents for more languages . It should be noted that the language configuration needs to follow the BCP47 syntax, usually {language subtag}–{script subtag}–{country subtag}.

Create strings.xml

Create a file corresponding to the selected language in the res/values ​​directory strings.xml, the steps are as follows:

  1. Right-click the res folder and select New->Android Resource File.
image.png
  1. In the pop-up window, enter the file name strings, select Locale in Available qulifiers, and select the desired language.
image.png image.png
  1. In the creation strings.xml, configure the corresponding multilingual string (convenient for demonstration, use machine translation, not necessarily accurate).
image.png

Configure Manifest

AndroidManifestconfigure inlocale_config.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <application android:localeConfig="@xml/locale_config">
        ...
    </application>
</manifest>

If the device version is above Android 13, after completing this step, the user can already configure the preferred language in the system settings of the application.

The effect is as shown in the figure:

device-2023-07-08-14 -original-original.gif

Preferred language API

On devices with a version lower than Android 13, the language of the application can be configured individually through the preferred language API.

add dependencies

Add code in build.gradle under app module, as follows:

dependencies {
    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'androidx.appcompat:appcompat-resources:1.6.1'
}

use the API

AppCompatDelegateIf passed , getApplicationLocalesthe language configured by the current App can be obtained, and if passed, AppCompatDelegatethe setApplicationLocaleslanguage used by the App can be modified. The code is as follows:

class ChangeLanguageActivity : AppCompatActivity() {

    private val availableLanguage = arrayOf("zh", "en", "ru", "ko", "ja")
    private val availableLanguageDisplayName = arrayOf("Chinese", "English", "Russian", "korean", "Japanese")

    private var currentLanguage = "zh"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = LayoutChangeLanguageActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // 获取当前的语言
        currentLanguage = if (AppCompatDelegate.getApplicationLocales().isEmpty) {
            Locale.getDefault().toLanguageTag()
        } else {
            AppCompatDelegate.getApplicationLocales()[0]?.toLanguageTag() ?: ""
        }
        binding.includeTitle.tvTitle.text = "Change Language Example"
        binding.btnChangeLanguage.setOnClickListener {
            AlertDialog.Builder(this)
                .setTitle("Chose Language")
                .setSingleChoiceItems(availableLanguageDisplayName, availableLanguageDisplayName.indexOf(currentLanguage)) { _, which ->
                    currentLanguage = availableLanguage[which]
                }
                .setPositiveButton("ok") { dialog, _ ->
                    // 切换语言
                    AppCompatDelegate.setApplicationLocales(LocaleListCompat.forLanguageTags(currentLanguage))
                    dialog?.dismiss()
                }
                .setNegativeButton("cancel") { dialog, _ ->
                    dialog?.dismiss()
                }
                .create()
                .show()
        }
    }
}

The effect is as shown in the figure:

device-2023-07-07-18 -middle-original.gif

Save selected language

As you can see in the rendering above, after using the API to change the application language, it will become invalid if you close the App and open it again. You can Manifestconfigure to AppLocalesMetadataHolderServiceautomatically save the currently selected language in , so that the previously configured language will be used by default every time the App is opened. The code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    <application>
        <service
            android:name="androidx.appcompat.app.AppLocalesMetadataHolderService"
            android:enabled="false"
            android:exported="false">
            <meta-data
                android:name="autoStoreLocales"
                android:value="true" />
        </service>
    </application>
</manifest>

The effect is as shown in the figure:

device-2023-07-07-18 -middle-original.gif

example

Demo code has been added in Example Demo.

ExampleDemo github

ExampleDemo gitee

Guess you like

Origin juejin.im/post/7253102401451049015