In this blog, we will learn on how to identify RTL language in your android application.
The reason for writing this blog is pretty clear from the title itself and there are many ways to get this done.
But while working on including Farsi language in my application I ran into some problem and I needed to fix this problem, the reason was pretty straight that the orientation was supposed to be RTL, but with all the approaches I knew I was not getting the orientation to be RTL.
When I checked all the approaches, they were in some manner getting the orientation from the locale, which in turn was getting the direction from the Character class, and thus for some reason, the RTL flag for Farsi was not coming as it should be.
Then after pondering upon the issue, I got to know that the directionality returned for Farsi is a bit different than the Default RTL languages.
So, when I looked up in the Character class, I found that there are actually two flags that are returned for RTL languages viz. DIRECTIONALITY_RIGHT_TO_LEFT and DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC. If you will look just below this line then you will see some other flags also with the RIGHT_TO_LEFT indicators in them, but I never got them in return values.
Now it was all clear and all I needed to include this also in my code as RTL identifier.
Let’s see what I followed :
APPROACH :
- Get the current Locale Object of the application.
- Get the display name of this locale object.
- Pass this display name’s first character to the Character.getDirectionality() function of the character class.
- Check the directionality integer returned with Character.DIRECTIONALITY_RIGHT_TO_LEFT || Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC;
- If the values matches the language is RTL Language.
CODE :
function is RTL()
1 2 3 4 5 6 |
public static boolean isRTL(Locale locale) { final int directionality = Character.getDirectionality(locale.getDisplayName().charAt(0)); return directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT || directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC; } |
using this function in the code
1 2 3 4 5 |
if (isRTL(Locale.getDefault())){ Log.d(TAG, "isRTL : " +"true" ); }else { Log.d(TAG, "isRTL : " +"false"); } |
That’s all.
Keep coding and keep sharing 🙂