我需要能够检测用户正在查看的当前语言是否是阿拉伯语的RTL(从右到左)语言。
目前我只是根据系统属性user.language中的语言代码检测到这一点,但必须有更好的方法。
答案 0 :(得分:13)
ComponentOrientation.getOrientation(new Locale(System.getProperty("user.language"))).isLeftToRight();
答案 1 :(得分:7)
我觉得有点脏,依赖于AWT课程,这些课程已经过时了,我正在处理BCP-47语言代码,所以我最终从Google Closure模板中复制了这些代码:
/**
* A regular expression for matching right-to-left language codes.
* See {@link #isRtlLanguage} for the design.
*/
private static final Pattern RtlLocalesRe = Pattern.compile(
"^(ar|dv|he|iw|fa|nqo|ps|sd|ug|ur|yi|.*[-_](Arab|Hebr|Thaa|Nkoo|Tfng))" +
"(?!.*[-_](Latn|Cyrl)($|-|_))($|-|_)");
/**
* Check if a BCP 47 / III language code indicates an RTL language, i.e. either:
* - a language code explicitly specifying one of the right-to-left scripts,
* e.g. "az-Arab", or<p>
* - a language code specifying one of the languages normally written in a
* right-to-left script, e.g. "fa" (Farsi), except ones explicitly specifying
* Latin or Cyrillic script (which are the usual LTR alternatives).<p>
* The list of right-to-left scripts appears in the 100-199 range in
* http://www.unicode.org/iso15924/iso15924-num.html, of which Arabic and
* Hebrew are by far the most widely used. We also recognize Thaana, N'Ko, and
* Tifinagh, which also have significant modern usage. The rest (Syriac,
* Samaritan, Mandaic, etc.) seem to have extremely limited or no modern usage
* and are not recognized.
* The languages usually written in a right-to-left script are taken as those
* with Suppress-Script: Hebr|Arab|Thaa|Nkoo|Tfng in
* http://www.iana.org/assignments/language-subtag-registry,
* as well as Sindhi (sd) and Uyghur (ug).
* The presence of other subtags of the language code, e.g. regions like EG
* (Egypt), is ignored.
*/
public static boolean isRtlLanguage(String languageString) {
return languageString != null &&
RtlLocalesRe.matcher(languageString).find();
}
答案 2 :(得分:0)
TextUtils.getLayoutDirectionFromLocale(locale)
答案 3 :(得分:0)
添加一个布尔资源is_rtl
(假设为)
res/values/values.xml
中
<bool name="is_rtl">false</bool>
res/values-ldrtl/values.xml
中
<bool name="is_rtl">true</bool>
然后,在Java中,您可以获得此布尔资源,并立即知道用户是否在RTL语言环境中。