Android主要用InputMethodManager来对软键盘进行管理。手动显示或隐藏软键盘前需要先获取InputMethodManager。InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
//...
}
为了避免NullPointException,需要判断imm实例是否为null。
显示软键盘
InputMethodManager显示软键盘有三个方法:boolean showSoftInput (View view, int flags)
boolean showSoftInput (View view, int flags, ResultReceiver resultReceiver)
void showSoftInputFromInputMethod (IBinder token, int flags)
一般情况下会选择使用第一个方法,即两个参数的showSoftInput,基于两个原因:showSolftInput的resultReceiver参数用于接收完成输入后返回结果,但由于它可以长时间存在jvm里而不会被gc,使用它需要注意内存泄漏。
showSoftInputFromInputMethod使用不当会存在失效的情况。
所有这里只介绍showSoftInput (View view, int flags)
先上示例showKeyBoard(View view) {