Android輸入法之——如何在代碼中強制切換輸入法

轉載自:http://xiaohang.org/2011/02/android%E8%BE%93%E5%85%A5%E6%B3%95%E4%B9%8B%E2%80%94%E2%80%94%E5%A6%82%E4%BD%95%E5%9C%A8%E4%BB%A3%E7%A0%81%E4%B8%AD%E5%BC%BA%E5%88%B6%E5%88%87%E6%8D%A2%E8%BE%93%E5%85%A5%E6%B3%95/

由於工作需要,追蹤Android輸入法Framework中了關於輸入法切換的實現過程或者說是API調用的部分。
找到如下兩個API:

1.InputMethodManager.setInputMethod (IBinder token, String id)
public void setInputMethod (IBinder token, String id)
Force switch to a new input method component. This can only be called from the currently active input method, as validated by the given token.
Parameters
token Supplies the identifying token given to an input method when it was started, which allows it to perform this operation on itself.
id The unique identifier for the new input method to be switched to.
此函數,當然是可以實現輸入法的強制切換的,但是,IBinder的獲得卻需要一定的權限,調用起來需要比較深入,哥們能力有限專研的一陣子未果。日後,再做深入探討吧。哪位仁兄有解,歡迎留言,不勝感激!!

2.InputMethodService.switchInputMethod(String id)
public void switchInputMethod (String id)
Since: API Level 3 Force switch to a new input method, as identified by id. This input method will be destroyed, and the requested one started on the current input field.
Parameters
id Unique identifier of the new input method ot start.
相對第一個API來說,這個卻簡單的多。最直觀來看的話,就是這裏不用獲得相應的IBinder!我們幾乎已經勝利了,但是,還是需要點破這層紙的。
首先,關於該API在何處調用?
該API屬於類InputMethodService,而每個輸入應用的入口類又都是繼承於該類的,所以,在輸入法入口類調用該API就可以了。比如,Google的SDK中給出的Google拼音輸入法,就在類PinyinIME.java中調用就可以了!
再者,關於參數id?
從定義來看,它是一個String類型,看Google的解釋也未免籠統。經小可仔細專研,原來,是這樣的,還是用例子來說吧,依然選擇上述例子。 Google拼音輸入法的id就是:com.android.inputmethod.pinyin/.PinyinIME。完整的調用方法就 是:switchInputMethod(“com.android.inputmethod.pinyin/.PinyinIME”);
那麼,如果不在入口類中如何調用呢?
在需要調用的類中定義:private PinyinIME mImeService;
需要的地方調用就可以了:mImeService.switchInputMethod(“com.android.inputmethod.pinyin/.PinyinIME”);
OK!打完收工!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章