[英]Get keyboard language or detect user input language in 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
異常。
有沒有辦法讓鍵盤選擇語言? 如果沒有我怎么能檢測用戶輸入應用程序的語言?
以下是我為獲取可用輸入語言所做的工作:
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);
}
}
}
}
您可以通過首先檢測設備鍵盤的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”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.