在Android中获取键盘语言或检测用户输入语言

时间:2013-07-16 07:50:46

标签: java android android-softkeyboard

问题描述

我正在尝试检测当前选定的键盘语言。为此,我使用以下代码:

代码

/* 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();

但是应用程序会在NoSuchMethodError函数上出现getCurrentInputMethodSubtype异常。

问题

有没有办法让键盘选择语言?如果没有,我怎么能检测用户输入应用程序的语言?

5 个答案:

答案 0 :(得分:5)

以下是我为获取可用输入语言所做的工作:

private void printInputLanguages() {
   InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
   List<InputMethodInfo> ims = imm.getEnabledInputMethodList();

   for (InputMethodInfo method : ims) {
       List<InputMethodSubtype> 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);
          }
       }
   }
}

答案 1 :(得分:3)

首先检测设备键盘的区域设置,然后从中获取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将提供您的键盘语言。希望这会有所帮助。

答案 2 :(得分:1)

没有。有一个手机区域设置,但键盘可能会被设计忽略(许多键盘允许您在双键用户的键盘内切换语言)。没有键盘的API可以向操作系统报告。

答案 3 :(得分:1)

第一种方法

获取设备的选定语言。这可能有助于你

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();

答案 4 :(得分:-2)

如果您想获得所选设备的语言。这可能有助于你

Locale.getDefault().getDisplayLanguage();

您可能也会这样做:

Locale.getDefault().toString(),它提供了一个完全标识语言环境的字符串,例如“EN_US”。

相关问题