Android language setting app

Android App-Specific Language Change Programmatically Using Kotlin

By default, Android will try to load resources based on the System language that is set on the user’s phone. Therefore, if a Tamil language user, Kavi, with her Android set to the Tamil language opened our android application on her phone, she’d see an app localized to her own language.

But what if another user wants to use the Tamil language for his android application on an Android that has its default language set to English?

To deal with this, we will have to programmatically update the locale of our android application to override the default locale set in the user’s system. Here we gonna do ask the user to choose the language and switch the language in application only.

Let’s start with creating new resource files for the Tamil language using Android Studio’s resource file wizard.

Firstly, right-click on the res folder and choose “New -> Android resource file”: It will show prompt like this type file name as strings.xml

Here select the language,

It will generate XML for you then you can put sample string like below.

English default look like

Newly added Langauge Tamil look like

That’s it we configured strings locale.

Now let’s create a ContextUtils utility class to hold our locale updating methods. Place this within a utils package on the android application, as follows:

  1. Configuration.localethe field was deprecated in API level 24 (Nougat). This was put in place by Android API developers to make coders move to the use of getters and setters instead of directly accessing variables.
  2. This was marked as the preferred way of setting up locales (instead of using the direct accessor or setLocale(java.util.Locale)) starting from API level 24.
  3. Before API level 24, developers could directly access the configuration.locale field to change it as they pleased.

Then we can use this method to apply locale changes.

Create BaseActivity which is extends AppCompatActivity and it must be inherited by other activities.

We going to use attachBaseContext override method to update locale configuration to ACTIVITY so it will reflect on all other activities which are extended by.

Q: What is the use of AttachBaseContext?

A: The attachBaseContext function of the ContextWrapper class is making sure the context is attached only once. ContextThemeWrapper applies theme from application or Activity which is defined as android:theme in the AndroidManifest.xml file. Since both Application and Service do not need theme, they inherit it directly from ContextWrapper . During the activity creation, application and service are initiated, a new ContextImpl object is created each time and it implements functions in Context .

LanguageChooseActivity → MainActvity

Here we store inside SharedPreference a string that contains language code like for tamil →“ta” , English →”en”, Hindi →”hi” etc…

This code used to identify the Language using Locale(«language-code»)

After applying in base activity wherever the strings are used automatically translated.

Below is the sample activity that extends BaseActivity().

Just extends BaseActivity is enough and see the magic. 😉 Hope user won’t get lost in application.

Источник

How to Change the Whole App Language in Android Programmatically?

Android 7.0(API level 24) provides support for multilingual users, allowing the users to select multiple locales in the setting. A Locale object represents a specific geographical, political, or cultural region. Operations that required these Locale to perform a task are called locale-sensitive and uses the Locale to tailor information for the user. For example, displaying a number is a locale-sensitive operation so, the number should be formatted according to the conventions of the user’s native region, culture, or country.

Example

In this example, we are going to create a simple application in which the user has the option to select his desired language-English or Hindi. This will change the language of the whole application. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.

Step by Step Implementation

Step 1: Create A New Project

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

Step 2: Create Resource Files

In this step, we are required to create a string resource file for the Hindi language. Go to app > res > values > right-click > New > Value Resource File and name it as strings. Now, we have to choose qualifiers as Locale from the available list and select the language as Hindi from the drop-down list. Below is the picture of the steps to be performed.

Источник

Changing App language in Android

In your app, you can add as many languages as you want. By languages, I mean the language of the text that we see in any mobile application. For example, if you have English, French, and Hindi users, then you can have language support for all these languages. Like «Hello» in English will become «Bonjour» in French and «नमस्ते» in Hindi.

But how can we change the language? That’s the topic for this blog. In this blog, we will learn how to change the App locale in Android with ease.

By default, you have English as your default language for the whole app and the text corresponding to the English language will be there in our strings.xml file. So, similarly, for other languages, you need to add their strings.xml file.

So, basically Android loads the resources related to language based on the system locale setting. For example, if the language of your Android phone is English, then strings.xml of English will be loaded by Android. We do not have to do anything extra here.

But, many times, we want our users to change the language of our App only by selecting the preferred language and not by changing the language of our Android phone. So, let’s see how to add this.

Читайте также:  Android зависает при включении

First of all, create a project in Android Studio. Here, we will be having 2 activities:

  • MainActivity: This will contain one welcome TextView and two Buttons, one for opening the next activity in the English language and the other for opening the next activity in the Hindi language.
  • LanguageActivity: This will simply contain a TextView displaying some message. The message will be shown in English if the language of the app is English and the message will be shown in Hindi if the language of the app is Hindi.

So, let’s start with the MainActivity. The following is the code for the activity_main.xml file:

Here, we have 1 TextView and 2 Buttons.

Similarly, you can add one TextView in your LanguageActivity. The following is the XML code for the same:

And finally, here is the strings.xml file:

So, we are done with our prerequisite part. Now, we are ready to add a new language to our app. Follow the below steps to do so:

  • Right Click on res > New > Android Resource File
  • Put the file name as strings.xml
  • Select the option of Locale

  • Select the locale for Hindi with code «hi»

  • Click on Ok and now, you will be having two values directory i.e. the default one with the name values and the other with name values-hi . The default one will contain the strings.xml file for the default language(in our case, English) and the values-hi will contain the strings.xml file for the Hindi language.

Now, you need to put all the values of all the strings that we defined in our default strings.xml file for our new Hindi strings.xml file.

But there are certain cases where we want to keep the text of the default language. For example, the name of the App should be the same for all languages. In our case, we just need to translate the message that is shown on the LanguageActivity and not all texts like AppName, WelcomeMessage, etc.

So, for that, we need to set translatable to false in our default strings.xml file(the English one). For example:

Similarly, you can set translatable = «false» for other string values as well. Now, for the other strings that you want to translate, you can simply add their values in the strings.xml file of the Hindi language. For example, the code of strings.xml (hi) will be:

In this way, you are telling the Android app to use the string value according to the locale of the App.

Now, our final task is to change the locale or simply the language of the app when we click on the button. For this, add the below function in your MainActivity.kt file:

In the above code, pass the context and the language code and then start the LanguageActivity . For example:

Now, when you open the LangaugeActivity, then you can see the changes in the language.

Points to keep in mind:

  • Whenever an activity is loaded then the corresponding string.xml file is loaded at that time only. For example, if the current locale of your app is English and on button click, you changed it to Hindi. Then no change on that particular activity will be observed because the string file of that activity is already loaded. But if you move to some other activity and then come back to the first activity, then you will see the language changes. If you want to see instant changes, then you need to refresh the activity after the change of the locale.
  • In some Android Versions, you might not see the locale change if you are opening some WebView in your app. Always take care of the case when you load the WebView for the very first time. One possible option is to set again the locale after loading the WebView.
  • You need to handle the case of orientation change of your activity. The locale will be reset in this case as well, so handle this as well.
  • It is recommended by Android to not change the locale at runtime. So, you can avoid this if the use-case of language is not that much important in your app.

This is how you can change the locale of your App. That’s it for this blog. Hope you enjoyed this blog.

Источник

Android localization: Step-by-step

With Android’s expansive popularity among people from all over the world, getting Android localization done right has become a crucial step in app development.

You may be a novice developer building your very first Android app, or you may be an expert programmer getting yet another Android app under your belt among a dozen others. But, let me ask you a question. For whom are you creating this app? In other words, what’s your target audience?

Hopefully, you want your app to grow and be used beyond your local community; to reach across continents, and ultimately worldwide. Here’s the sticking point; most of the world does not speak English. Sooner or later, you will need to support multiple languages.

This warrants the need for your Android application to be localized.

In this article, we will explain how to get started with Android localization using step-by-step examples.

We will cover the following topics in this tutorial:

  • Android i18n/l10n.
  • Adding resources with the help of Android Studio l10n facilities.
  • Programmatically switching Locale using proxied Context .
  • Localization-related deprecations across different API levels.
  • Noun pluralization with Android quantity strings.
  • Date-time localization using java.text.DateFormat.getDateTimeInstance() .

The first version of this post was written by Arturs Ziborovs.

The source code is available on Github.

Localize Your Android App

First and foremost, let’s create an Android project with an empty Activity to be used for our localization purposes. We can use a template provided by Android Studio. For demonstration purposes, let’s make a project with the following configuration:

Note: You may choose any API version less than or equal to API 30 (latest version at the time of writing).

Add Some Elements

Now it’s time to put some content into this empty MainActivity . Open up the activity_main.xml file located the inside res/layout directory of our android-i18n project. Let’s put a simple TextView with the string «Hello world» in it:

Next, let’s run this app and see. It should look like this:

But, there’s an issue here; the «Hello world!» string value is embedded directly within the layout description of the test_text_view itself. As you may already know, it is an elementary level bad practice to hardcode string values within the code of an application. On top of that, you would need this text to dynamically change in case your Android localization app’s user decides to change the application’s language to another.

Читайте также:  App center для android

Add Language Resources

How about stocking up our Android app with some language resources holding localization-related values? These will act as static assets holding language content for multiple languages.

Android SDK provides a specific structure to hold Android app resources. Following this pattern, look inside the res/values directory and you’ll be able to find a strings.xml resource file holding the text strings used in our android-i18n application.

Let’s add a new string resource in strings.xml to hold the «Hello world!» string:

Note that we provided a my_string_name key to refer to our sample text string value «Hello World!» . It is acceptable to do so in simple contexts such as this, but please make it a habit to come up with self-explanatory names for your keys. For instance, try settings_language_title or settings_language_description .

Add More Resources

We can call upon the help of Android Studio l10n support to conveniently add another resource file.

Let’s create a new resource file for the Russian language using Android Studio’s resource file wizard.

Firstly, right-click on the res folder and choose “New -> Android resource file”:

The wizard will let you choose from a list of available Resource qualifiers for your new folder.

Qualifiers are used by the system to decide which resources to load based on the user’s device configuration, such as selected language, screen size, country code, etc. Keep in mind that these qualifiers can be used for other types of resources such as images or layouts as well. You can refer to this Android documentation to learn more about Android app resources.

Secondly, select Locale from the list of available qualifiers and add it to the chosen qualifiers. Now to add a Russian language resource file, choose ru: Russian from the language list. We can keep the Specific Region Only: setting at its default value Any Region since we will not be narrowing down our localization to particular regions for this example.

Thirdly, set the File name as «strings.xml» . You will notice that Android Studio has automatically set a Directory Name of values_ru .

Then lastly, click the OK button and a «strings.xml» file inside a res/values-ru/ directory should be opened.

Now, let’s add Russian language resources to this XML file. Be sure to add the same keys as previously when creating the «strings.xml» for the English US language:

Refer the Resources

Once we have our resources properly set up for two languages, let’s reference them on our TextView . Open up the TextView in the res/values/activity_main.xml layout. Refer the resource key my_string_name to the android:text attribute of the TextView :

Refer Resources Dynamically

If you need to dynamically change the strings used in a TextView , you can do it programmatically within MainActivity :

  1. Set the title of this Activity’s ActionBar to the string resource app_name .
  2. Set the text of test_text_view to string resource my_string_name .

Now our android-i18n application is successfully localized for two languages. Let’s run our app again and see what it looks like:

You might be thinking…

It looks the same as before, duh.

But as a matter of fact, we’re no longer showing a hardcoded «Hello world!» value on the TextView. Instead, in its place, we are now representing test_text_view resource localized according to our Android device’s System language.

We can test this out by running our android-i18n application on an Android device with its System language set to Russian.

Following the same pattern, we can now expose our application not just in the form of US English, but also in countless other languages.

However, how do we switch our app to another language without touching the device settings? We’ll explore this in the next section.

Change Application Locale Programmatically

By default, Android will try to load resources based on the System language that is set on the user’s phone. Therefore, if a Russian user, Ann, with her Android set to the Russian language opened our android-i18n application on her phone, she’d see an app localized to her own language.

But what if another user wants to use the Russian language for his android-i18n application on an Android that has its default language set to English?

To deal with this, we will have to programmatically update the locale of our android-i18n application to override the default locale set in the user’s system.

Let’s create a ContextUtils utility class to hold our locale updating methods. Place this within a utils package on the android-i18n application, as follows:

Extend the class with ContextWrapper to allow it to create ContextWrapper objects holding a proxy implementation of Context .

Let’s code an updateLocale method that returns a wrapper Context holding a modified locale of the current activity context, like so:

  1. Create a new configuration object using the resource configuration in the given Context .
  2. Create a locale list containing the locale to which we plan to switch.
  3. Assign the default locale for this instance of the JVM to the locale at the first index on this list. Since there’s only one locale present in our example, this will inadvertently set the locale on localeToSwitchTo variable as the default locale.
  4. Set the locale list we created in step #2 to the configuration object we created in step #1 using a setter.
  5. Directly modify the locale field in the configuration object we created in step #1 with the localeToSwitchTo parameter on the method.
  6. Set the current context variable to a new Context object whose resources are adjusted to match the given configuration.
  7. Store the newly updated configuration in the resources field in the given context.
  8. Return a new ContextUtils object created by passing the context variable as a parameter to ContextUtils constructor.

Deprecations Across Different Levels

If you skimmed through the code for the updateLocale method, you must have seen that the implementation faces changes based on the Android build version of the application. This is due to various deprecations that have occurred along the course of Android API levels.

Let’s reanalyze a few code snippets from the updateLocale method to get a general idea of these deprecations, and how they warranted the code changes that followed:

  1. Configuration.locale field was deprecated in API level 24 (Nougat). This was put in place by Android API developers to make coders move to the use of getters and setters instead of directly accessing variables.
  2. This was marked as the preferred way of setting up locales (instead of using the direct accessor or setLocale(java.util.Locale)) starting from API level 24.
  3. Before API level 24, developers could directly access the configuration.locale field to change it as they pleased.
  1. Resources.updateConfiguration method was deprecated from API 25 (Nougat++).
  2. Context.createConfigurationContext has been around since API level 17 (Jelly Bean MR1). However, with the deprecation of the Resources.updateConfiguration method, this was the workaround approach to update the configuration of a context.
  3. Before API level 25, developers could use the Resources.updateConfiguration method to update a context configuration.
Читайте также:  Все для прокачки android

With our ContextUtils sorted out, let’s see how to use it on our app to change locale. Let’s open up the MainActivity class on our android-i18n application and put in an overriding method like the below:

This code firstly creates a new ContextWrapper with its locale updated to the Russian language. Secondly, it passes this newly created ContextWrapper to be attached as the context used in MainActivity . Afterwards, when this activity loads on startup, it will work on a context that has its locale set to Russian.

That’s it! Simply run the application and voila, the text has successfully been localized without any manual changes to the Android’s System language on our end.

Some Android Localization Extras

Let’s take a look at a few other things you’ll surely run into on your Android app localization journey.

How to Pluralize Nouns

When dealing with nouns, we need them to be properly pluralized according to a particular language’s standards. For instance, we don’t want our Android application to say “I have 3 cat” instead of “3 cats“, right? This is where Android’s built-in support for quantity strings(plurals) comes in handy. Let’s try it out!

First off, add some TextViews to your activity_main.xml :

These will consecutively hold text for one, few, and many quantities of objects.

As you may know, pluralization rules usually differ from language to language. English only has two main forms such as:

While the Russian has three variations when counting whole numbers, like:

Therefore, we will have to create separate plurals elements for each of these languages.

Let’s add these pluralizations in our project’s respective language resource files:

  • On res/values/strings.xml :
  • In res/values-ru/strings.xml :

In case you’re interested, the syntax for plurals elements are documented in the syntax section of the Android documentation for quantity strings.

Now let’s set some plural text values in the TextViews we created earlier. Add these lines to the onCreate method of the MainActivity class:

Refer to the documentation on Resources.getQuantityString method to get an idea of its parameter usage.

The result should look like this for each localization:

What about Date and Time?

We can call upon the help of the getDateTimeInstance method provided in the DateFormat class to handle localization of date and time on Android projects.

Firstly, let’s add a simple TextView within our android-i18n application’s activity_main.xml :

Then, let’s fill this TextView with text showing a localized date and time upon launch of our app.

Open up the MainActivity class and put this code in its onCreate method:

  1. Create a new Date object with a no-arguments constructor and allocate it to currentDateTime . Using this constructor makes the Date object represent the exact time (and date) at which it was allocated.
  2. DateFormat.getDateTimeInstance static factory method is used to automatically format currentDateTime for the current locale.

Run the Android app with each localization. It should now show the current date and time successfully localized to the corresponding locales:

Lokalise saves the day

So my friend, if you’ve come this far in the article, you must be dead set on somehow getting your Android app internationalized. But let’s face it, do you — or your team — really have the time to learn all of these new classes and methods and deal with deprecated variables, just to localize your app?

Yeah, I heard you. You don’t.

As you add more features and expand to more markets, your app will grow to thousands of strings in dozens of languages. Surely you could use the help of a proper Translation Management System to carry out your Android app’s i18n while keeping yourself sane, am I right?

That’s where Lokalise comes in. Let’s see how it works.

First off, create an account or log in to Lokalise.

On the Lokalise dashboard, select Upload to upload the language resource files of the project you plan to localize. In the case of the Android application we created during the tutorial, you can choose the strings.xml files we created for the two languages.

Note: If the detected language is incorrect, feel free to select the correct language from the dropdown.

Click the Import the files button to complete the resource uploading process.

Head back to the project’s Lokalise Dashboard. You will see the resources neatly organized like so:

That was pretty fun and easy, wasn’t it? The Lokalise editor is a feature-rich and user-friendly interface that includes collaborative translation, translation quality assurance, automatic translation suggestions, professional translation services, and loads more to be used for your Android app’s localization.

How to Edit Your Translations

No need to change countless text files if you need to change some resource values. Let’s see how easy it is with Lokalise. Suppose you are a dog person, click on «cat» and replace it with «dog» in the popup:

Then click the Download button to download your new translations and perform the following steps:

  1. Choose the «Android Resources» file format from the list.
  2. Press the Build and download button to obtain a ZIP archive with your new translations.
  3. Replace the old files in your project with the new ones.

Likewise, Lokalise automatically generates the requested translation files with all your project languages for the specified platform.

Conclusion

In this tutorial, we checked out how to localize an Android application to multiple locales. We explored various API deprecations that caused Android l10n to become not quite a walk in the park. We also delved into ways we could effectively tackle these deprecations. Next, saw how we can switch to different languages; either by changing the device’s language or forcefully switching the application to a modified Context .

In addition to this, we looked into how we can pluralize nouns using Android quantity strings, and how to perform date-time localization.

And with that, my watch is ended. Please don’t hesitate to leave a comment if you have any questions.

Источник

Оцените статью