方法一
InputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
// 显示或者隐藏输入法
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
源码解析:
/*
* This method toggles the input method window display.
* If the input window is already displayed, it gets hidden.
* If not the input window will be displayed.
* @param showFlags Provides additional operating flags. May be
* 0 or have the {@link #SHOW_IMPLICIT},
* {@link #SHOW_FORCED} bit set.
* @param hideFlags Provides additional operating flags. May be
* 0 or have the {@link #HIDE_IMPLICIT_ONLY},
* {@link #HIDE_NOT_ALWAYS} bit set.
* @hide
*/
public void toggleSoftInput(int showFlags, int hideFlags) {
if (mCurMethod != null) {
try {
mCurMethod.toggleSoftInput(showFlags, hideFlags);
} catch (RemoteException e) {
}
}
}
由此可知这个方法是用来切换软件输入法在窗体中的显示状态。如若要确保切换至隐藏状态的话,则需要判断输入法的显示状态,可通过以下方式判断:
imm.isActive()
源码解析:
/**
* Return true if any view is currently active in the input method.
*/
public boolean isActive() {
checkFocus();
synchronized (mH) {
return mServedView != null && mCurrentTextBoxAttribute != null;
}
}
即通过判断输入法中任意视图是否处于激活状态来判断输入法的状态。
方法二
// 隐藏输入法
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
// 隐藏输入法
imm.hideSoftInputFromWindow(getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
源码解析:
/**
* Synonym for {@link #hideSoftInputFromWindow(IBinder, int, ResultReceiver)}
* without a result: request to hide the soft input window from the
* context of the window that is currently accepting input.
*
* @param windowToken The token of the window that is making the request,
* as returned by {@link View#getWindowToken() View.getWindowToken()}.
* @param flags Provides additional operating flags. Currently may be
* 0 or have the {@link #HIDE_IMPLICIT_ONLY} bit set.
*/
public boolean hideSoftInputFromWindow(IBinder windowToken, int flags) {
return hideSoftInputFromWindow(windowToken, flags, null);
}
可知:请求隐藏来自当前正在接受输入的窗口上下文的输入窗口,简单点说就是请求隐藏指定窗口处于激活状态的输入法。其中windowToken为指定窗口令牌。如是在activity中使用则可通过一下方法获取:
xxActivity.this.getCurrentFocus().getWindowToken()
在自定义view中则可直接通过getWindowToken()。