What is rtl android

Android RTL Support

The majority of mobile apps are designed LTR (Left to Right), that is because the vast majority of the world languages are written from Left to Right and only a small number of languages are written from Right to Left such as Arabic. Most of mobile developers never worry about this issue since most of the apps are not intended to target users from regions using languages written from Right to Left also because it was not as easy as it is now to support both directions. As the competition started heating up, it became important to globalize the apps and provide localized versions in order to reach more users and improve app downloads. Moreover, the rise of mobile apps development in these Arabic-speaking countries made it crucial to provide RTL support.

It is very easy to provide localized versions for different LTR languages in android apps by just providing another strings.xml file under values-XX folder where XX is the language code which contains all the translations for the strings used in this app.

Android 4.2(API 17) released in 2013 has provided full Native support for RTL layouts; it has become very easy to take advantage of this feature and all you need are just few simple changes in your code.

How to start:

First of all, in your Manifest.xml file, you need to declare under the element android:supportsRtl=”true”

Use Start and End layout properties instead of Left and Right, respectively. In LTR layouts, start means left and end means right ; however, in RTL start means right and end means left .

Examples for these properties are Padding, Margin, TextView Drawables, Gravity, LayoutGravity, and layout alignments.

In case you need a custom layout in for RTL, just provide the layout with the same name under ldrtl qualifier

Drawables:

Usually the icons you are using are direction independent, so you will not need alternative drawable for RTL; however, there are some cases where you will have to, for example, the back button.

Normally for LTR this is how it looks like:

If you use the same button for RTL this is how it will look like:

While what you need is this:

You can achieve this by mirroring the icon using an external tool and add the new icon with the same name in drawable-ldrtl folder, or just use the forward navigation button and change it’s name in “drawable-ldrtl” folder

In case your minimum SDK is 19, you can use android:autoMirrored=”true” attribute in vector drawables where as the name implies will automatically mirror the icon vertically in case the direction is RTL

Text appearance:

For more control over the text appearance, you can use these attributes

android:textAlignment — attribute for setting the alignment of a component’s text.

android:textDirection — attribute for setting the direction of a component’s text.

Use gravity for textAlignment which is default for the root view. The gravity determines the alignment, ALIGN_NORMAL, ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction

Читайте также:  Dumb ways to die для андроид

Use locale for textDirection which makes the paragraph direction is coming from the system Locale.

To apply these attributes you can add it each textview or globally by adding it to main AppTheme in styles.xml

To know about the variations of textAlignment and textDirection attributes check

Application Language Preference:

All the mentioned-above is sufficient to provide RTL layout and in case the app is supposed to follow the device’s language then nothing more is needed. However, in case the user is supposed to be able to choose a specific language, then few more lines of code are needed.

To change the Locale of the application programmatically use the following

Then restart the activity to apply the changes

However, if the user changed the language of the device, the app will be affected, and in order to prevent that use configChanges attribute under each element in the Manifest and list Locale and layoutDirection as the changes you would like to handle manually.

This prevents the application from recreating the activity then override onConfigurationChanged in the activity

Then you can reapply the user’s configuration for the app again in onConfigurationChanged

Fallback to LTR:

It is possible to force a certain layout direction using android:layoutDirection , it can be useful, for example, when using a ViewPager and TabLayout, the default sliding animation is LTR when doesn’t change in RTL. So a possible solution is to keep the android:layoutDirection=”ltr” and reverse the tabs orders and fragments programmatically. Y ou can check at runtime if the layout is RTL using this method in TextUtils getLayoutDirectionFromLocale .

Another example is the phone number field, numbers direction are always LTR which means it does not change with language direction, so a possible solution is to use Left and Right instead of Start and End or use android:layoutDirection=”ltr” for the parent view.

Hopefully these tips could help you with your developing any application in Arabic. Please don’t hesitate to comment below if you have any questions regarding RTL support in android or anything regarding android development in general. Finally please refer to the official android blog for more information about native RTL support.

Источник

RTL Support on Android. Here is all you need to know

Apr 14, 2017 · 4 min read

There comes a point in an app’s lifecycle when you decide to widen your audience. Although your app works great and you have a huge number of daily downloads, not everyone is happy. Why 🤔? No RTL (Right to Left) Layout support.

Few languages such as Arabic, Hebrew, or Persian are written from Right to Left. To handle them, Android supports RTL layouts from API 17+ i.e., Android 4.2 (Jelly Bean) .

Getting Started

  • In order to support RTL in your app, you first need to add android:supportsRtl=»true» to the element in your manifest file.

Woohoo… 🎉Done. Your app now supports RTL. But lets see how it looks. You can check your app in RTL mode by doing one of two things.

  • Select one of the RTL languages as your device language.
  • Or from Developer Options in Settings , check Force RTL layout Direction . I find this option more convenient but, do note, this does not change your System language.

XML Layouts

Yo u ’ll need to make the following changes in all your Layouts

  • If your app only supports API ≥ 17 , replace all the layout_marginLeft/layout_marginReft/paddingLeft/paddingRight or any other Left and Right layout property with Start and End equivalent. For example android:paddingLeft will be replaced with android:paddingStart .
  • If your app supports API then instead of replacing the Left and Right layout properties, add their Start and End layout property equivalent alongside.
Читайте также:  Яркости экрана для android

There is a much easier way to do the above changes without going through all the files and then doing it manually. Android Studio can do this for you. Just go to Android Studio > Refactor > Add RTL support where possible…

I would recommend you checking your app once after applying this change as you might not want all your Layouts/Views to be RTL. If you want to force any layout to LTR then just add android:layoutDirection=»ltr» to that view.

Drawables

Time to search for all those drawables that you would want to be mirrored for RTL. Since resources can have variants based on device aspects like Orientation, Screen Density, API version, you can also have variants for different Layout Directions i.e., RTL or LTR. All you need to do is add the RTL variants of the drawables that you want to be mirrored.

📌 Small Tip :

If your Toolbar defines back arrow nav icon like this
app:navigationIcon=»?attr/homeAsUpIndicator»
This back button is consistent with Layout Directions.
But only works on API 23+ 😣, below that it just points Left.

And what if you don’t have RTL variant for your drawables? You can use android:autoMirrored=»true» . But this works on api 19+ only. If you want to mirror Drawables or any View on API android:rotationY=»@integer/locale_mirror_flip» to the View you want to be mirrored. And define

res/values/integers.xml

res/values-ldrtl/integers.xml

I use this trick to mirror one of the Progress Indicator that doesn’t support RTL. This works on API 11+.

Animations

Animations that use X axis for transitions will not work properly. For example TranslateAnimation — You will need to add a RTL variant for these as well.
For example: android:fromXDelta=»-100%p» will become android:fromXDelta=»100%p» in RTL variant of this animation,
android:pivotX=»25%» will become android:pivotX=»75%» .

Java Files

I would recommend defining all animations, layout, etc as xml resource only. Because RTL support for those programmatically defined layouts and animations is painful. Also, the compilation will take more time if you modify a Java file instead of XML.

If you still find these defined in your java files then this is what you’ll need to do

  • Programmatically defined Animations with X axis values need to have different values for RTL, as the X axis always starts from Left in both layout directions. Basically any X anywhere in android means from left.
  • If you have setMargin(left, top, right, bottom) then also add setMarginStart(start) and setMarginEnd(end) .
  • setPadding(left, top, right, bottom) will be replaced with setPaddingRelative(start, top, end, bottom) .
  • setGravity(Gravity.LEFT/RIGHT) will be replaced with setGravity(Gravity.START/END) .
  • Any other layout property like LayoutParams rules for RelativeLayout will also need to be changed.
  • All those Horizontal RecyclerView, ListView, ViewPager , etc will need your attention as well.
    For Example : A Horizontal RecyclerView can use setStackFromEnd(true) on it’s LayoutManager in case of RTL layout.
  • If you want Layout Direction of a View on runtime then use
    ViewCompat. getLayoutDirection(view)
    Note : This always returns LTR if called from the Constructor of a View.
  • If you want Layout Direction from a Context then use
    Configuration config = context.getResources().getConfiguration();
    if (config.getLayoutDirection() == View. LAYOUT_DIRECTION_RTL) <
    //RTL
    >
Читайте также:  Movie maker для android

Extras

If you have completed all of the above then I believe you should have pretty good RTL Support. There are few more things you can look at for your final touch.

Conclusion

Support for RTL is not that difficult on Android. I wish I had supported it from day 1 instead of doing it at a later stage in my app. If you found something missing or have suggestions then do comment.

Источник

Идентификация языка RTL в Android

Есть ли способ идентифицировать язык RTL (справа налево), помимо проверки кода языка на всех языках RTL?

Поскольку API 17+ позволяет несколько ресурсов для RTL и LTR, я полагаю, должен быть способ, по крайней мере, от API 17.

ОТВЕТЫ

Ответ 1

Ответ 2

@cyanide ответ имеет правильный подход, но критическая ошибка.

Character.getDirectionality возвращает тип Двунаправленный (bidi) символ. Текст слева направо — предсказуемый тип L, а справа налево также предсказуемо тип R. BUT, арабский текст возвращает другой тип, тип AL.

Я добавил проверку как для типа R, так и для типа AL, а затем вручную протестировал каждый RTL-язык Android, в который входят: иврит (Израиль), арабский (Египет) и арабский (Израиль).

Как вы можете видеть, это исключает другие права налево, поэтому я был обеспокоен тем, что, когда Android добавит эти языки, может возникнуть аналогичная проблема, и никто не заметил бы сразу.

Итак, я тестировал вручную каждый язык RTL.

  • Арабский (العربية) = тип AL
  • Курдский (کوردی) = тип AL
  • Farsi (فارسی) = тип AL
  • Урду (اردو) = тип AL
  • Иврит (עברית) = тип R
  • Идиш (ייִדיש) = тип R

Итак, похоже, что это должно отлично работать:

Спасибо @cyanide за отправку меня в правильном направлении!

Ответ 3

Если вы используете библиотеку поддержки, вы можете сделать следующее:

Ответ 4

Вы можете использовать TextUtilsCompat из библиотеки поддержки.

Ответ 5

Там действительно простой способ проверить направление макета представления, но он возвращается к LTR на устройствах с интерфейсом API 17:

класс ViewUtils поставляется с библиотекой поддержки v7, поэтому он должен быть доступен уже, если вы используете библиотеку appcompat.

Ответ 6

Я собрал много информации и, наконец, создал свой, надеюсь, завершенный класс RTLUtils.

Это позволяет узнать, является ли данный Locale или View ‘RTL’ 🙂

Ответ 7

Вы можете проверить это, если хотите проверить API ниже 17

ИЛИ для API 17 или выше

Ответ 8

Для более точного контроля над пользовательским интерфейсом вашего приложения в режиме LTR и RTL, Android 4.2 включает в себя следующие новые API, которые помогут управлять компонентами View:

Ответ 9

Если вы посмотрите на код LayoutUtil.getLayoutDirectionFromLocale() (и, я полагаю, Confuiguration.getLayoutDirection() ), он заканчивает анализом стартовой буквы отображаемого имени локали, используя Character.getDirectionality .

Поскольку Character.getDirectionality был рядом с Android 1, следующий код будет совместим со всеми релизами Android (даже те, которые не поддерживают RTL правильно:)):

Ответ 10

При создании библиотеки вам также всегда нужно проверить, поддерживает ли приложение RTL, используя

Когда приложение выполняется в локальном RTL, но оно не объявлено в манифесте android:supportsRtl=»true» , тогда он работает в режиме LTR.

Ответ 11

Это будет работать во всех SDKS:

Ответ 12

Просто используйте этот код:

Это будет работать для всех приложений Java API.

Ответ 13

Ответ 14

Поскольку устройства на английском языке поддерживают RTL, вы можете использовать этот код в своем MainActivity для изменения языка устройства на английском языке, и вам не нужно поддерживать код поддержки RTL.

Ответ 15

Вы можете определить, является ли строка RTL/LTR с помощью Bidi. Пример:

Источник

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