Identifying RTL language in Android

前端 未结 16 1694
既然无缘
既然无缘 2020-11-28 06:59

Is there a way to identify RTL (right-to-left) language, apart from testing language code against all RTL languages?

Since API 17+ allows several resources for RTL a

16条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 07:26

    I gathered many information and finally made my own, hopefully complete, RTLUtils class.

    It allows to know if a given Locale or View is 'RTL' :-)

    package com.elementique.shared.lang;
    
    import java.util.Collections;
    import java.util.HashSet;
    import java.util.Locale;
    import java.util.Set;
    
    import android.support.v4.view.ViewCompat;
    import android.view.View;
    
    public class RTLUtils
    {
    
        private static final Set RTL;
    
        static
        {
            Set lang = new HashSet();
            lang.add("ar"); // Arabic
            lang.add("dv"); // Divehi
            lang.add("fa"); // Persian (Farsi)
            lang.add("ha"); // Hausa
            lang.add("he"); // Hebrew
            lang.add("iw"); // Hebrew (old code)
            lang.add("ji"); // Yiddish (old code)
            lang.add("ps"); // Pashto, Pushto
            lang.add("ur"); // Urdu
            lang.add("yi"); // Yiddish
            RTL = Collections.unmodifiableSet(lang);
        }
    
        public static boolean isRTL(Locale locale)
        {
            if(locale == null)
                return false;
    
            // Character.getDirectionality(locale.getDisplayName().charAt(0))
            // can lead to NPE (Java 7 bug)
            // https://bugs.openjdk.java.net/browse/JDK-6992272?page=com.atlassian.streams.streams-jira-plugin:activity-stream-issue-tab
            // using hard coded list of locale instead
            return RTL.contains(locale.getLanguage());
        }
    
        public static boolean isRTL(View view)
        {
            if(view == null)
                return false;
    
            // config.getLayoutDirection() only available since 4.2
            // -> using ViewCompat instead (from Android support library)
            if (ViewCompat.getLayoutDirection(view) == View.LAYOUT_DIRECTION_RTL)
            {
                return true;
            }
            return false;
        }
    }
    

提交回复
热议问题