use locale (ltr/rtl) for gravity in TextView

agrajag picture agrajag · Dec 14, 2015 · Viewed 13.7k times · Source

I have a simple TextView which should have android:gravity="left" for ltr system locales and android:gravity="right" for rtl system locales.

The obvious choice would be: android:gravity="start" but then e.g. english text will always be left-aligned and hebrew right-aligned.

Here is how it looks with android:gravity="start":

LTR locale:

|          לורם|   // incorrect
|test           |  // correct

RTL locale:

|          לורם|  // correct
|test           |  // incorrect

it's supposed to look like that:

LTR locale:

|לורם           |  
|test            | 

RTL locale:

|          לורם|  
|           test| 

Is it possible to do that without using a layout-ldrtl folder with a modified xml file? This would complicate development a lot because I would have to edit a lot of layout files twice...

edit: a solution for API 17+ is enough. I wrote system locale, but actually I'm allowing the user to change the app language like that:

Configuration configuration = context.getResources().getConfiguration();
configuration.setLayoutDirection(selectedLocale);
configuration.locale = selectedLocale;
context.getResources().updateConfiguration(configuration, context.getResources().getDisplayMetrics());

so it would be great if this locale would be considered for the rtl <-> ltr choice.

Answer

atabouraya picture atabouraya · May 19, 2016

I had this problem too, you can use these properties with the TextView

android:textDirection="locale"
android:textAlignment="gravity"

or just add it to the Base App Theme in styles.xml`

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:textColorPrimary">@android:color/white</item>
    <item name="android:textColorSecondary">@android:color/white</item>
    <item name="colorButtonNormal">@color/colorAccent</item>
    <item name="android:textAlignment">gravity</item>
    <item name="android:textDirection">locale</item>
    </style>`

That worked for me.