- Локализация. חתול מדען (хатуль мадан) — кот учёный
- Просмотр и создание локализованных строк в режиме дизайна
- Непереводимая игра слов с использованием местных идиоматических выражений
- Поддержка письма справа налево
- Несколько локалей
- Best Practices for Android Localization, Revisited and Expanded
- Why Is Android Localization Important?
- What is the Difference between Localization (i10n) and Internationalization (i18n)?
- What are Best Practices and Why Do They Matter?
- Select Target Markets
- Design Layouts with Localization in Mind
- Support both LTR and RTL
- String Localization
- Do Not Hardcode Strings
- Provide Context
- Add Attributes to Untranslatable Text
- Placeholders in Strings
- Line Breakers and Word Wrappers
- Using Fonts that Support Multiple Languages
- Find Translators
Локализация. חתול מדען (хатуль мадан) — кот учёный
В статье, посвященной ресурсам, мы уже затрагивали эту тему с теоретической точки зрения. Разберем теперь практическую часть. Мы уже умеем пользоваться строковыми ресурсами и меняли строчки, например, Hello, World на Здравствуй, Мир! Но на самом деле это не совсем правильный подход. Для профессионально написанного приложения лучше использовать другой подход. А именно, локализацию.
Что это значит? Мы не будем менять строчку Hello, World, которая будет считаться строкой по умолчанию, а создадим новый локализованный ресурс. Это даст нам дополнительное преимущество, если пользователь запустит приложение на телефоне с английской локалью, то он увидит текст на знакомом ему языке. Если приложение запустит русский пользователь, то он увидит текст на русском языке. Согласитесь — очень удобно.
Напишем приложение, которое будет поддерживать английскую и русскую локализации. По умолчанию будет использоваться английская локализация. В этом случае, если на телефоне не будет найден нужный локализованный ресурс, то будет применяться английский вариант.
Чтобы не усложнять материал, воспользуемся стандартным приложением, который мы изучали в самом начале. Создадим новый проект «LocaleApp», но на этот раз мы не будем трогать файл strings.xml в каталоге res/values.
Для русской локализации необходимо создать новый подкаталог values-ru в том же каталоге res. Если вы планируете создавать локализацию только для русского языка, то название каталога не трудно запомнить и вы можете создать папку вручную через res | New | Directory. Но вряд ли вы запомните названия других папок. Поэтому покажу способ создания с помощью мастера студии.
Щёлкаем правой кнопкой мыши на папке res и выбираем New | Android resource directory. В диалоговом окне в левой части Available qualifiers: выбираем пункт Locale и переносим его в правую часть Chosen qualifiers: с помощью кнопки с двумя стрелками вправо. В появившейся третьей колонке выбираем нужные языки, например, русский. Вы увидите, что в поле Directory name автоматически появится нужное название папки. Дополнительно вы можете указать и регион в колонке Specific Region Only
В режиме Android вы можете не увидеть созданную папку, поэтому временно переключитесь в режим Project. Скопируйте файл res/values/strings.xml и вставьте его в новую папку. Можете вернуться в прежний режим. Если папка не пуста, то она уже видна.
Изменим его содержание.
В английской версии им соответствуют ресурсы
Запустим приложение и увидим, что текст выводится на русском, если у вас на эмуляторе или реальном устройстве выбраны русские настройки.
Как перейти на американскую локаль? Идём в Настройки→Язык и клавиатура→Выбрать язык. Выбираем английский язык English (United States). Снова запускаем приложение в эмуляторе или на телефоне. Теперь наше приложение будет выглядеть так:
Ресурсы из каталога res/values считаются ресурсами по умолчанию. Они отображаются в том случае, когда система не найдёт ресурсы для текущей локали устройства. В нашем случае, при выборе любого языка, кроме русского будет использоваться res/values. Если мы захотим разделить англичан и американцев, тогда придётся создавать два каталога: res/values-en-rUK и res/values-en-rUS. Обратите внимание, что перед кодом второй части ставится буква ‘r’. Иными словами, мы определяем не только язык, но и регион.
Проведем несколько экспериментов. Удалим из файла res/values-ru/strings.xml строковый ресурс hello_world с текстом Здравствуй, Мир!. Сохраним изменения и запустим проект на устройстве с русским языком. Платформа заменила отсутствующий в локализации ресурс дефолтным английским.
Продолжим опыты и поступим наоборот — удалим теперь ресурс из файла res/values/strings.xml. На устройстве выберем какой-нибудь другой язык, например, итальянский. В этом случае вы увидите что-то непонятное, скорее всего вы получите сообщение об ошибке.
Отсюда можно сделать вывод, что вам необходимо следить за ресурсами по умолчанию. Старайтесь проконтролировать, чтобы ваше приложение всегда содержало все необходимые ресурсы по умолчанию, а уже потом можете начинать локализацию приложения. Для этого вам достаточно будет скопировать файл в новый подкаталог и отредактировать его.
На самом деле локализовать можно не только строковые ресурсы. В разных странах принято рисовать какой-нибудь объект в соответствии со своими традициями, например, изображение почтового ящика. В этом случае вы можете создать каталог /res/drawable-de, в котором будут находиться изображения, предназначенные для немцев.
В коде вы обращаетесь к нужным ресурсам следующим образом:
Система сама подставит нужную строку. Явно указать, что хочется использовать ресурс на конкретном языке, у вас не получится.
Спустя продолжительное время один из читателей подсказал, как всё-таки задействовать локальный ресурс. Объяснять код не буду, сами поймёте, когда наберётесь опыта.
Просмотр и создание локализованных строк в режиме дизайна
Чтобы увидеть, как меняется текст в различных локализованных версиях вашего приложения, необязательно запускать приложение в эмуляторе. Можно в студии на панели инструментов щёлкнуть на значке глобуса и выбрать из выпадающего списка нужный вам пункт (он появится после того, как вы создадите необходимые локализованные ресурсы), и все локализованные строчки сразу поменяются на экране активности.
Можно сразу создать локализованный файл через удобный мастер. Там же в меню есть пункт Edit Translations. , который выводит диалоговое окно со списком уже имеющихся строковых ресурсов из вашей программы (раньше). Вам нужно выбрать язык для перевода, а затем заполнить в таблице нужную колонку.
После того, как вы завершите перевод всех ресурсов, нажимаете на кнопку OK и у вас появится готовая папка с новым файлом strings.xml для выбранной локализации.
Сейчас в студии вместо диалогового окна выводится окно редактора, в котором можно редактировать текст.
Непереводимая игра слов с использованием местных идиоматических выражений
Если вы решили использовать локализацию на разных языках, то можете встретиться с одной проблемой. Предположим, вы перевели только несколько строковых ресурсов и в один прекрасный день решили выложить программу в магазин приложений. Android Studio при сборке подписанного приложения может заругаться, что вы перевели не все строки. Есть два способа обхода проблемы. Вы можете использовать атрибут translatable=»false», чтобы указать среде разработке, что данная строка не требует перевода:
В окне редактора это сделать проще через флажки в столбце Untranslatable.
Второй вариант — явно указать, что все строки в файле не нужно переводить с помощью tools:ignore=»MissingTranslation».
Есть ещё один вариант, когда непереводимые строки размещаются не в ресурсе strings.xml, а в другом файле под именем donottranslate.xml.
Когда вы исправите строковые ресурсы, то избавьтесь от ошибок через Project | Clean. и попытайтесь собрать приложение заново.
Поддержка письма справа налево
Арабы и некоторые другие народы используют непривычную для европейцев схему написания текстов справа налево. В Android 4.2 появилась поддержка данного режима. В блоге (англ.) Native RTL support in Android 4.2 рассказано о некоторых вещах по этой теме.
Теперь вы можете писать приложение для израильских военкоматов. Русские призывники в интервью офицерам душевного здоровья часто используют сочетание хатуль мадан (חתול מדען). Теперь вы знаете, как локализовать строки пушкинского стихотворения про кота учёного.
Несколько локалей
В Android 7.0 (API 24) пользователь может установить несколько локалей. В этом случае, если не будут найдены ресурсы для первой локали, то будут искаться ресурсы для второй локали. Таким образом, если француз знает два языка, например, французский и испанский, а в приложение не поддерживает французского, но поддерживает испанский, то пользователь увидит текст на испанском, а не на английском.
Источник
Best Practices for Android Localization, Revisited and Expanded
Being able to localize more complex Android apps in different languages isn’t a child’s play. In practice, you’d have to learn quite a few tricks before you get things rolling. In this guide, we’ll revisit the best practices for Android localization and go beyond the standard.
Why Is Android Localization Important?
We speak quite often about the importance of localization. No wonder! The statistics are quite clear. As reported by Statista, the number of mobile phone users globally has risen to 4.93 billion. According to a study by App Annie, an app market data and insights company, China and India surpass the US in terms of revenue generated by mobile apps. Non-English usage is even higher for Android-based applications. With regards to downloads and revenue in Google Play Store, the majority of the top five countries are non-English speaking countries.
It’s natural that people are more comfortable with using apps adapted to their own language. Therefore, supporting as many languages as possible can be a vital factor in staying ahead of your competitors.
What is the Difference between Localization (i10n) and Internationalization (i18n)?
Many people, including developers, often falsely use localization and internationalization as synonyms. Let’s get this thing clear before we go on. Internationalization is the process that prepares an app for localization. It will be much more difficult to localize your app after it has been completely built. Internationalization is a set of actions that you need to take at the development stage of your application, so it is easier to localize the app. In turn, localization is the process of customizing the content to make the app available in different languages.
This shows clearly that these two processes are inseparable so best practices for adapting software to multiple languages must be followed in both localization and Internationalization.
What are Best Practices and Why Do They Matter?
Best practices in the software development community are a set of informal rules that have been learned over time and can help improve the quality of software. It’s not all about writing time and space-efficient codes. Best practices include decisions that should be made over the entire development life cycle. By following best practices, you can reduce the cost and effort involved in the localizing process while making it scalable and easy to maintain.
Select Target Markets
The most important decision to be made in Android Localization is selecting the target markets. Localizing your application for a particular locale comes at a cost. Therefore, you shouldn’t try to localize your Android application for every language just because it’s possible.
Also, the cost of localizing your app is not the same for all languages. Localizing your app for French is usually easier than localizing for Chinese or Arabic. You should also carefully think about the return on investment. For example, if your app is only about American football, there is no point of localizing your app for India or China although they have the biggest market.
Design Layouts with Localization in Mind
Texts in different languages take different lengths. Let’s see how different languages communicate the same sentence.
- English: Let’s do Android localization to capture a bigger market
- German: Lassen Sie uns Android-Lokalisierung durchführen, um einen größeren Markt zu erschließen
- French: Faisons la localisation Android pour capturer un plus grand marché
- Chinese: 让我们做Android本地化来占领更大的市场
You can clearly see that each language requires a different amount of space for the same text. You need to account for the text expansion and contraction when creating Android UIs. The general rule is to add 30% extra space to UI elements to accommodate other languages.
There are three main design principles you should follow:
- You shouldn’t use fixed width/heights for UI elements (buttons, text fields menus, labels, images). Otherwise, texts could be displayed cropped or with excessive spaces when translated into other languages.
- Elements should be placed relative to each other. They should be placed on fixed coordinates. They have to be realigned according to translated languages.
- Containers and wrappers should be able to adjust their sizes according to the sizes of their contained elements.
Support both LTR and RTL
There are certain languages that read and write from right to left. Arabic and Hebrew are both good examples. You need to design layouts in such a way that they can flip entirely when necessary. This could be a bit of an expensive process and require many flows/procedures to follow. That’s why it is important to carefully select what languages you’re going to support before starting the development process. Usually, a modular design approach is considered the best approach for this situation.
String Localization
Strings are the most important objects in a localization process. They’re at the center of this tutorial. Let’s see what practices we need to follow for string localization.
Do Not Hardcode Strings
You shouldn’t hardcode strings in layouts. This is very tempting for a novice. However, this could be a serious issue when it comes time to localize your Android app.
Luckily, Android Studio warns us about this. If you have already added hardcoded string, Android Studio has a nice way to add them to string.xml file:
- Highlight the text
- Press Alt+Enter
- Click “Extract string resource”
- You will then get a dialogue box. You have to enter a preferred name to that string value.
- Now check in string.xml and layout page.
Provide Context
While simple applications only contain a few strings, larger applications may contain hundreds, even thousands of strings. You have to label them in a way that allows them to be easily differentiated. This is called providing context.
The first thing to remember when naming a string is to create a label with a meaning. For example,
Comments are often overlooked by many programmers. This is not a good practice.
You should add comments to every part of your code. The same theory applies to localization as well.
Add Attributes to Untranslatable Text
Not all strings need to be translated. For example, the name of a company does not need to be translated. You must clearly specify those strings it in the string.xml file. This can be done in two ways:
A. Use tags to enclose the text
B. Use an translatable=»false» attribute with your text.
Placeholders in Strings
Another mistake many novices make is concatenating Strings in Java code. This is a really poor practice. Instead, you should use placeholders whenever possible. For example, let’s say you want to have a dialog to greet a user.
Android can use %s according to each language.
Sometimes you want to display a set of names with a separator. But separators like comma ‘,’ could vary from language to language. You should declare your separator in the string.xml file and then use it in your code.
Line Breakers and Word Wrappers
Another interesting difference between different languages is how they separate words. Although many western languages use a space to separate words, East Asian languages like Chinese and Japanese don’t use spaces to separate words.
Consider the previous example:
- English: Let’s do Android localization to capture a bigger market
- Chinese: 让我们做Android本地化来占领更大的市场
You can’t see spaces in Chinese text. The Chinese language relies on syllable boundaries. Hence, usual word-wrapping and line-breaking algorithms in your application can cause problems.
You have to find a better routing to parse words in your application. This is crucial for when wrapping texts for layouts. There are several word segmentation algorithms that you can use.
Using Fonts that Support Multiple Languages
To keep a consistent look and feel across different languages, you need to be careful when selecting font types for your texts. Font choice can seriously impact the readability of the text. There are a few things to keep in mind.
You can characterize fonts in many ways such as serif or sans-serif, proportional or monospace.
But the most important characteristic that matters for translation is whether fonts are Unicode or non-Unicode (such as ASCII). Unicode fonts are created from Universal Coded Character Set (UCS) — a comprehensive set of characters and glyphs from multiple languages — encoded in a way that ensures those characters appear the same across platforms and systems. On the other hand, ASCII is specific to a certain language. ASCII might look pretty in English, but they are very limited in terms of translation. Therefore, you should be careful to use a Unicode-compliant font. Be careful, some fonts claim to be Unicode, but only support certain code-points. This could lead to multilingual issues.
The same font size may have different readability in different languages. For example, although 12px is readable in English, the same size could be difficult to read when translated to Japanese.
You have to change font sizes dynamically for each language. For that, you have to maintain separate style sheets for different languages which will include specific styles for each language.
Find Translators
Let’s add a few words on translation teams: This aspect can influence the success of localization more than anything. Web developers can’t translate your app. You need to enlist translators if you want to achieve that goal. Don’t rely on Google Translate when adapting your application. It might provide incorrect or out of context translations. It’s always better to rely on a professional translator.
Localization is a substantial topic. We were able here to cover a great deal of information, but there is more. The text is not the only thing that needs to be localized. You have to localize images, dates, and numbers.
We will discuss the topics mentioned above in upcoming tutorials. Eventually, we will build an application with all these best practices. In the meantime, if you’re already looking for an Android app localization tool, make sure you give Phrase a try and sign up for a free 14-day trial to see how it can streamline your localization processes.
Источник