在Android中获取键盘语言或检测用户输入语言
问题描述
我正在尝试检测当前选定的键盘语言。 为此,我使用以下代码:
码
/* Return the handle to a system-level service by name. The class of the returned * object varies by the requested name. */ InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); /* Returns the current input method subtype. This subtype is one of the subtypes in the * current input method. This method returns null when the current input method doesn't * have any input method subtype. */ InputMethodSubtype ims = imm.getCurrentInputMethodSubtype(); /* The locale of the subtype. This method returns the "locale" string parameter passed * to the constructor. */ String locale = ims.getLocale();
但是应用程序会对getCurrentInputMethodSubtype
函数产生NoSuchMethodError
exception。
题
有没有办法让键盘选择语言? 如果没有我怎么能检测用户输入应用程序的语言?
以下是我为获取可用输入语言所做的工作:
private void printInputLanguages() { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); List ims = imm.getEnabledInputMethodList(); for (InputMethodInfo method : ims) { List submethods = imm.getEnabledInputMethodSubtypeList(method, true); for (InputMethodSubtype submethod : submethods) { if (submethod.getMode().equals("keyboard")) { String currentLocale = submethod.getLocale(); Log.i(TAG, "Available input method locale: " + currentLocale); } } } }
您可以通过首先检测设备键盘的Locale
然后从中获取Locale
对象来获得键盘语言。 例如,
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodSubtype ims = imm.getCurrentInputMethodSubtype(); String localeString = ims.getLocale(); Locale locale = new Locale(localeString); String currentLanguage = locale.getDisplayLanguage();
在这里, currentLanguage
将提供您的键盘语言。 希望这可以帮助。
没有。有一个手机区域设置,但键盘可能会被设计忽略(许多键盘允许您在双键用户的键盘内切换语言)。 没有用于键盘的API可以向操作系统报告。
第一种方法
获取设备的选定语言。 这可能对你有帮助
Locale.getDefault().getLanguage() ---> en Locale.getDefault().getISO3Language() ---> eng Locale.getDefault().getCountry() ---> US Locale.getDefault().getISO3Country() ---> USA Locale.getDefault().toString() ---> en_US Locale.getDefault().getDisplayLanguage() ---> English Locale.getDefault().getDisplayCountry() ---> United States Locale.getDefault().getDisplayName() ---> English (United States)
第二种方法
您可以从当前区域设置中提取语言。 您可以通过标准Java API或使用Android Context来提取语言环境。 例如,下面两行是等价的:
String locale = context.getResources().getConfiguration().locale.getDisplayName(); String locale = java.util.Locale.getDefault().getDisplayName();
如果您想获得设备的选定语言。 这可能对你有帮助
Locale.getDefault().getDisplayLanguage();
你可能也这样做:
Locale.getDefault().toString()
,它给出一个完全标识语言环境的字符串,例如“en_US”。