Как изменить язык в Android Stuido?
Можно ли изменить язык среды разработки Android Studio? Если да то на какие языки и как?
У врачей общепринятым языком общения является латынь, даже деревенский фельдшер выписывая диагноз не преминет написать DS или щегольнет словечком анамнез. И в этом есть глубокая правда жизни — диагноз выписанный врачом в России поймет доктор даже где-нибудь в Африке — сам лично был свидетелем, когда в богом забытой Камбодже местный коновал спокойно разобрал каракули московского коллеги.
У нас, у прогеров/кодеров/девелоперов таковым является английский язык, это может нравиться или не нравиться, но это факт против которого бесполезно протестовать.
Так что надо знать английский язык, хотя бы в мере достаточной для того, чтобы пользоваться Android Studio.
Если вам, все таки неймется — возьмите файл resources_en.jar , который лежит в каталоге lib Android Studio, распакуйте его и переведите несколько тысяч ресурсных строчек на русский язык, типа:
JetBrains в свое время портировали Intellij IDEA (читай ту же Android Studio) на японский, но потом отказались, сказав, что дескать выхлоп был никакой. Это не стоило потраченных на локализацию усилий — японские девелоперы отнюдь не кинулись покупать IDEA 🙂
Локализация Android-приложений: о чем умалчивает документация
Локализация Android-приложений — намного более сложная задача, чем должна была бы быть. Описание в документации недостаточное: чтобы разобраться в происходящем «под капотом», нужно искать информацию во внешних источниках (на StackOverflow и в блогах) и тренироваться на базовых приложениях типа «Hello World».
В этой статье я разберу некоторые трудности процесса локализации, с которыми я столкнулся в своих приложениях. Решения, которые я буду приводить, не описаны в документации, поэтому я постараюсь быть максимально точным. (Примечание: термины «локаль» и «язык» в статье используются как синонимы.)
Многобукаф? Нажмите Ctrl-F и введите «вывод №».
Введение
В статье говорится о некоторых трудностях локализации, которые не рассматриваются в официальных ресурсах, — то есть, это не руководство по локализации «для чайников».
Перед чтением полезно будет изучить основы локализации Android-приложений (если вы еще не знакомы с этой темой) — прочтите следующие документы:
Проблема № 1. Приложение отображается не на том языке
Разберемся, что происходит в этом случае «под капотом». Допустим, языковые настройки телефона следующие:
Если перевести этот список в псевдокод, получим:
(Примечание. Язык по умолчанию для приложения определяется самим приложением. В одном случае это может быть польский, в другом — немецкий, и так далее, — это язык, файл которого размещен по пути values/strings.xml . К сожалению, указать системе Android язык по умолчанию для конкретного приложения нельзя — и мы с этой особенностью еще столкнемся позже.)
В основе этого списка лежит вроде бы простая логика. Однако в некоторых случаях приложение использует не тот язык, который должно было бы, и переключается на свою локаль по умолчанию, когда вы этого не ожидаете.
Чтобы увидеть, как это происходит, установите языковые настройки так, как показано на скриншоте выше, а затем создайте в Android Studio новое приложение из шаблона «Empty Activity». Откройте res/values/strings.xml и для строки app_name (название приложения) задайте значение «App In Default Language» («Приложение на языке по умолчанию»).
Запустите приложение и проверьте, чтобы оно работало. Название приложения появится слева вверху экрана.
Теперь добавим еще два файла values.xml :
Приложение можно снова запускать, но перед этим подумайте: какое значение app_name будет отображаться?
Разумно предположить, что это будет название на французском: испанский — предпочитаемый язык пользователя, но для этой локали файла strings.xml нет, поэтому система выберет следующий предпочитаемый язык — то есть, французский, для которого файл strings.xml у нас есть. Верно же?
А теперь запустите приложение:
Какого… Как так? Почему не на французском? У нас проблемы с логикой?
Нет. С нашей логикой всё в порядке. Дело в другом.
При создании проекта в Android Studio с ним идут кое-какие библиотеки по умолчанию. Взгляните на файл app/build.gradle :
В этих библиотеках содержатся файлы ресурсов для многих локалей — в том числе в них могут быть файлы values-es/strings.xml . Поэтому в скомпилированном и упакованном приложении у вас наверняка найдутся файлы strings.xml на испанском.
В итоге Android будет считать, что в приложении есть испанская локаль, и попытается найти app_name на испанском. Но мы эту переменную не определили, поэтому приложение берет ее в strings.xml по умолчанию и, соответственно, отображает строку «App In Default Language».
Такая ситуация называется загрязнением ресурсов: Android наступает на свои же грабли. Подробнее — здесь и здесь.
Чтобы обойти эту проблему, нужно объявить поддерживаемые языки в файле app/build.gradle .
Таким образом мы удаляет все ресурсы, за исключением французской и английской локали: это позволяет не только избежать загрязнения ресурсов, но и снизить размер APK-файла.
Измените файл app/build.gradle так, как показано выше, и перезапустите приложение:
Отлично. А если удалить французский язык из списка поддерживаемых?
Работает как ожидалось… за исключением одного случая.
«Один случай»
Давайте кое-что немного поменяем. Приведем список предпочитаемых языков к такому виду:
Теперь удалим папку resources/values-en из проекта и добавим новый файл values-es/strings.xml :
Итак, теперь у нас есть файл по умолчанию strings.xml (по-прежнему со строкой «App In Default Language»), его французская и испанская версии.
Удалим английский из списка поддерживаемых языков и добавим испанский:
Прежде чем запускать приложение, подумайте: на каком языке оно будет отображаться?
Если следовать той же логике, что и раньше, это должен быть испанский.
А теперь запустите приложение:
Черт побери… опять?! Мы же только что всё исправили! Или нет?
Поэкспериментировав несколько часов с таким поведением, я пришел к следующему заключению: где-то в кодовой базе Android предполагается, что ресурсы по умолчанию — на английском языке.
Это, на мой взгляд, неверно, но что уж поделаешь.
Выше я говорил, что resConfig удаляет ресурсы всех локалей, кроме объявленных… но я соврал: ресурсы по умолчанию resConfig НЕ УДАЛЯЕТ.
Итак, что у нас есть? В настройках пользователя английский указан как предпочитаемый язык. В пакете нашего приложения есть кое-какие строковые файлы по умолчанию (ведь они не были удалены), Android считает, что они на английском, и поэтому решает использовать файлы ресурсов по умолчанию.
Вывод № 1. Обязательно объявляйте языки, поддерживаемые в приложении, — с помощью resConfigs .
Вывод № 2. Если нужно, чтобы приложение поддерживало английский язык, файлы ресурсов по умолчанию должны быть на английском: Android рассчитывает на такое положение дел, поэтому так у вас будет меньше головной боли.
(Если вам английский в приложении не нужен, пропустите второй вывод.)
Проблема № 2. Как узнать текущую локаль приложения?
Казалось бы, найти ответ на такой вопрос должно быть легко, но, к сожалению, это не так: погуглив, вы увидите, что на StackOverflow об этом спрашивали, и не раз.
Причем там есть несколько вводящих в заблуждение ответов, например:
О каждом из этих методов я расскажу подробнее. Но прежде проясним кое-что очевидное, что путают советчики на StackOverflow:
Язык устройства != язык приложения
Первое — это язык, выбранный пользователем в настройках устройства. Второе — это язык, который Android решил использовать для конкретного приложения.
Узнать значение для языка устройства легко:
Итак, с языком устройства мы разобрались — перейдем к языку приложения. К сожалению, официального способа узнать локаль приложения во время выполнения, гарантированно не наткнувшись на ошибку, не существует.
Еще раз: не существует официального способа надежным образом узнать язык приложения во время выполнения.
Почему? Рассмотрим два случая:
Случай 1. Android нашел соответствующий файл «strings.xml» и использует его.
Случай 2. Android не нашел соответствующий файл «strings.xml» и использует файл по умолчанию.
В первом случае следующий код всегда будет возвращать правильное значение:
[[[[ НАЧАЛО БОЛЬШОГО ПРИМЕЧАНИЯ. Ребята на StackOverflow предлагают использовать Locale.getDefault() . Чем это отличается от только что описанного способа?
Я рекомендую почитать документацию по классу Locale. Если вкратце, то Locale.getDefault() используется для целей самой JVM: некоторые операции зависят от локали (например, выбор формата дат), и если не указать для них язык, JVM будет использовать значение, получаемое методом Locale.getDefault() .
Но самое главное отличие в том, что Locale.getDefault() определяется во время запуска приложения, и единственный способ изменить это значение — вызвать Locale.setDefault(новаяЛокаль) самостоятельно. Другими словами, если пользователь изменит настройки языка по умолчанию во время работы приложения, то Locale.getDefault() всё равно будет возвращать значение, определенное во время запуска.
А вот метод getResources().getConfiguration().getLocales().get(0) всегда будет давать актуальное значение (если вы его не кешировали, конечно).
КОНЕЦ БОЛЬШОГО ПРИМЕЧАНИЯ ]]]]
Ладно. Это был первый случай. А что насчет второго?
К сожалению, для случая 2 получить текущую локаль приложения нельзя. Нет официального способа узнать, какой файл strings.xml используется системой Android: локализованный или по умолчанию. Если применить способ для случая 1, мы просто получим локаль устройства.
Еще раз: если у вас случай 2, то метод getResources().getConfiguration().getLocales.get(0) вернет вам локаль устройства, а не приложения.
Однако для решения этой задачи есть обходной путь: нужно добавить в каждый из файлов strings.xml специальную строку (допустим, это будет current_locale ). В испанской версии strings.xml будет current_locale = ‘es’ , в итальянской — current_locale = ‘it’ , в файле по умолчанию — current_locale = ‘en’ (смотрите второй вывод статьи). Теперь достаточно будет в коде приложения вызвать следующий метод: getString(R.strings.current_locale)
Вывод № 3. Получение текущей локали устройства: Resources.getSystem().getConfiguration().getLocales().get(0) . Если уровень API равен 23 или ниже: Resources.getSystem().getConfiguration().locale .
Вывод № 4. Не существует надежного официального способа получить текущую локаль стандартными методами. Но есть обходной путь — см. чуть выше.
Проблема № 3. Как получить список предпочитаемых языков устройства?
В руководствах по Android сказано, что для этого есть новый API — LocaleList (для Android API с уровня 24). Теоретически, при вызове LocaleList.getDefault() вы должны получить список предпочитаемых языков пользователя, заданный в настройках, и он не должен зависеть от приложения — по крайней мере, так говорится в руководствах…
Я поэкспериментировал с LocaleList.getDefault() и могу сказать, что этот метод не всегда возвращает список предпочитаемых языков точно как в настройках.
В каких случаях бывает несоответствие? Проиллюстрирую на примере: предположим, немецкий НЕ ВЫБРАН как предпочитаемый язык и ваше приложение его тоже не поддерживает. Сделаем так:
Каким-то образом в списке, возвращенном методом LocaleList.getDefault() , оказался немецкий… хотя ни телефон, ни приложение его не поддерживают. Смотрим документацию LocaleList.getDefault() :
«Результат обязательно включает в себя локаль по умолчанию, получаемую из Locale.getDefault(), но не обязательно в верхней части списка. Если локаль по умолчанию не вверху списка, это значит, что система установила в качестве ее одну из других предпочитаемых локалей пользователя, заключив, что основной вариант не поддерживается, но вторичный поддерживается.
Внимание: для API >= 24 список LocaleList по умолчанию изменится, если вызвать Locale.setDefault(). В этом методе это учитывается: проверяется вывод Locale.getDefault() и при необходимости пересчитывается список LocaleList по умолчанию.»
Чего-о-о? Я прочел это трижды и всё равно не понял.
Давайте лучше я сам расскажу, как получить список предпочитаемых локалей на устройстве — и это будет последний вывод статьи.
Вывод № 5. Получение списка предпочитаемых локалей устройства (заданных в настройках): Resources.getSystem().getConfiguration().getLocales() . Это применимо только в API уровня 24 и выше: раньше в качестве предпочитаемого пользователь мог выбрать только один язык.
Заключение
В документации (а также в кодовой базе) Android не учитываются многие варианты использования локализации, и это может быть неприятно, поскольку разработчикам приходится учитывать крайние случаи, и делается это не всегда удобным и логичным образом.
Надеюсь, в этой статье мне удалось объяснить, как Android работает с локализацией, и какой API лучше выбрать для конкретного случая.
О переводчике
Перевод статьи выполнен в Alconost.
Alconost занимается локализацией игр, приложений и сайтов на 70 языков. Переводчики-носители языка, лингвистическое тестирование, облачная платформа с API, непрерывная локализация, менеджеры проектов 24/7, любые форматы строковых ресурсов.
Мы также делаем рекламные и обучающие видеоролики — для сайтов, продающие, имиджевые, рекламные, обучающие, тизеры, эксплейнеры, трейлеры для Google Play и App Store.
Как русифицировать android studio
Completing the CAPTCHA proves you are a human and gives you temporary access to the web property.
What can I do to prevent this in the future?
If you are on a personal connection, like at home, you can run an anti-virus scan on your device to make sure it is not infected with malware.
If you are at an office or shared network, you can ask the network administrator to run a scan across the network looking for misconfigured or infected devices.
Another way to prevent getting this page in the future is to use Privacy Pass. You may need to download version 2.0 now from the Chrome Web Store.
Cloudflare Ray ID: 71aa35bba94eb8b4 • Your IP : 82.102.23.104 • Performance & security by Cloudflare
Google Android — это несложно
Друзья, помогите пожалуйста, в Android Studio вместо русского такая вот проблема:
Re: Android Studio и русский язык
Re: Android Studio и русский язык
Re: Android Studio и русский язык
Справа снизу глянь
Я так и не понял в чем там проблема. У меня была похожая беда, точнее такая же. Сейчас проблема ушла, но я снес ОС (правда по другим причинам). Первый вариант, который поможет, это поставить кирилицу, ну а второй, . ну а второго я не знаю =)
могу еще сказать, что настройки кодировки есть в File>settings>File encoding
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 to join a dozen others. But, let me ask you a question: Who are you creating this app for? In other words, what’s your target audience?
Hopefully, you want your app to grow and be used beyond your local community; to reach the across continents, and ultimately go global. 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 to localize your Android application.
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 features.
- 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() .
- Setup and use of Lokalise OTA (over the air).
The first version of this post was written by Arturs Ziborovs.
The source code is available on GitHub.
How to 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 up to and including API 31 (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 in the 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 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 application’s user decides to change the app’s language.
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.
The 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’ve 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 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 of 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 when creating the «strings.xml» for English US:
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 , as follows:
- Set the title of this activity’s ActionBar to the string resource app_name .
- Set the text of test_text_view to the 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 the 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 present our application not just in 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 the application locale programmatically
By default, Android will try to load resources based on the system language set on the user’s device. 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 Russian 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:
- Create a new configuration object using the resource configuration in the given Context .
- Create a locale list containing the locale to which we plan to switch.
- 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 the localeToSwitchTo variable as the default locale.
- Set the locale list we created in step 2 to the configuration object we created in step 1 using a setter.
- Directly modify the locale field in the configuration object we created in step 1 with the localeToSwitchTo parameter on the method.
- Set the current context variable to a new Context object whose resources are adjusted to match the given configuration.
- Store the newly updated configuration in the resources field in the given context.
- Return a new ContextUtils object created by passing the context variable as a parameter to the ContextUtils constructor.
Deprecations across different levels
If you skimmed through the code for the updateLocale method, you might have seen that the implementation faces changes based on the application Android build version. This is due to various deprecations that have occurred through 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:
- The Configuration.locale field was deprecated in API level 24 (Nougat). This was put in place by Android API developers to make coders move to using getters and setters instead of directly accessing variables.
- 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.
- Before API level 24, developers could directly access the configuration.locale field to change it as they wished.
- The Resources.updateConfiguration method was deprecated from API 25 (Nougat++).
- 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.
- Before API level 25, developers could use the Resources.updateConfiguration method to update a context configuration.
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 . Afterward, 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 voilà, 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, i.e.:
- 1 cat
- 2 cats
While Russian has three variations when counting whole numbers, i.e.:
- 1 кот
- 2 кота
- 5 кошек
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:
- In res/values/strings.xml :
- In res/values-ru/strings.xml :
In case you’re interested, the syntax for plurals elements is 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 the 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 getDateTimeInstance method provided in the DateFormat class to handle the localization of date and time in 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:
- 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.
- The 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—either option will bring you to the Lokalise dashboard:
Secondly, click New project to start creating your localization project:
Thirdly, select Upload files 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 Editor tab of the project’s Lokalise dashboard. You will see the resources neatly organized, like so:
Now, you might be thinking…
Okay, Lokalise has my project’s language resources. How exactly is this useful for me or my organization?
Time to see how!
Generate resource bundle
No need to change countless text files if you need to change some resource values. With Lokalise, you can make resource value changes in a nice UI, and download automatically generated translation files for all your project’s locales for the specified platform.
For instance, suppose you are a dog person and wanted to change the resources to display dog values instead of cat. Simply click on «cat» in the resource values in the Lokalise dashboard and replace it with «dog» in the popup:
Then click the Download tab to download your new translations by performing the following simple steps:
- Choose the «Android Resources» file format from the list.
- Press the Build and download button to obtain a ZIP archive with your new translations.
- Replace the old files in your project with the new ones.
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.
“On the disk” to “Over the air”
In short, you still had to manually download resources, update, and rebuild or redeploy the whole application in the previous step, right? But, in this information age where everything’s in the cloud, isn’t there an easier way to make resource value changes for an app?
Yes, there is. Say hello to Lokalise OTA (over the air) where Lokalise sends your localizations straight over to your mobile app! How much more convenient can it get? Let’s see how you can set this up.
Firstly, head over to the Download tab on the Lokalise dashboard. Instead of “Android Resources (.xml)”, let’s change it to “Lokalise Android SDK” this time around. Then, we’ll press Build only to instruct Lokalise to generate an Android Bundle holding all your localizations:
This will take you to a bundle version management page where you can manage the generated bundles as you please:
How to update localization values
Each time your app needs any language resource value changes:
- Update the localization values in the Lokalise Editor.
- Generate a new Lokalise Android SDK bundle.
- Set the new bundle as the Production bundle and save the changes.
Secondly, let’s introduce Lokalise to your android-i18n application by adding the following to its top-level .gradle file:
Thirdly, let us add the Lokalise Android SDK dependency to your android-i18n app’s module-level .gradle :
Finally, it’s time to initialize the Lokalise Android SDK in your android-i18n app.
A few prerequisites
Head over to your Lokalise project’s dashboard and click on Settings under the More. tab. Here, take note of the Project ID, click Generate new token , and note down the resulting token value as well:
In order to let Lokalise handle its localizations throughout the app, we’d need to initialize the SDK before other processes start. Let’s achieve this by adding a custom Application class inheriting from android.app.Application to your android-i18n app:
Important note: Make sure to always place these lines right after the call to super.onCreate() .
- Initialize the Lokalise SDK by calling the Lokalise.init method. Remember to pass the SDK token and project ID noted down in the previous step as the method parameters.
- Bring the latest localization values from Lokalise over to the android-i18n project.
Let’s not forget to introduce this MyApplication to our android-i18n project’s AndroidManifest.xml file: https://gist.github.com/bodrovis/a283d44aee447d0a338f801943568faa
Now it’s time to ask your android-i18n application to use an Activity context that has the Lokalise SDK injected into it. We’ll make this happen by opening the MainActivity inside your android-i18n project and changing its attachBaseContext method:
You’re good to go! Next time, all updated localizations on the latest bundle will be sent over the air straight to your android-i18n app!
Test it out
Firstly, let’s navigate to the Editor tab of your Lokalise project dashboard. Then, let us change the values for “my_string_name” to say hello not just to the world, but to the whole universe!
Secondly, navigate to the Download tab and generate a new bundle by selecting the “Lokalise Android SDK” format and pressing Build only .
Finally, set the newly created bundle as the Production bundle and click Save changes :
Running our android-i18n application now should reflect the change on both localizations:
In the US English locale:
In the Russian locale:
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 less of 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 . Then, we discovered how Lokalise helps us swiftly retrieve our localizations to our Android app OTA (over the air).
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.
Русские Блоги
Android Studio установить плагин перевода (Перевести)
Android Studio установить плагин перевода (Перевести)
Процесс установки плагина:
Сначала откройте настройки AS: File ==> settings
Схема процесса:
(Примечание: вам, возможно, придется потянуть вниз, чтобы найти его . )
После завершения установки посмотрите его настройки
Конечно, вы также можете изменить сочетания клавиш
Какую комбинацию клавиш вы хотите изменить, просто нажмите и щелкните правой кнопкой мыши, чтобы выбрать параметр Добавить сочетание клавиш. Если вам не нужна предыдущая комбинация клавиш, щелкните правой кнопкой мыши, чтобы удалить ее.
Интеллектуальная рекомендация
Меч относится к предложению + 43: количество N сиша + Java
Оригинальное название: бросить кубики на землю, все точки кости сталкиваются с точкой точки кости. Введите n, напечатали вероятность всех возможных значений. (6 сторон каждой кости, точки от 1 до 6) Р.
Введение в Python 4
функция ввода Использование функции Функция input () является функцией ввода. Функция input () — это функция ввода. Когда вы пишете вопрос в скобках функции, функция input () будет отображать вопрос в.
Основные операции в R 01
Повторите основную операцию секретной книги ниндзя языка R учителя Се Иихуэй.
Мастерство, создание американской легенды очистки воды
Мастера — это не только технические специалисты и квалифицированные мастера, которые могут решить некоторые практические проблемы в производстве и жизни, но также авангарды, которые могут руководить п.
курсы памяти Лу Feifei (а, понимать память понимания мозга)
Понимание памяти, что память? Понимание памяти, что память? 1 Понимание мозга 2 Что такое память Функция 3 Память 3.1 общие воспоминания путь 3.2 Факторы, влияющие на память 4 запоминающий материал Че.