Android通过代码主动弹出或隐藏输入法软键盘

软键盘的弹出一般是在用户点击Edittext获取焦点后自动弹出,隐藏的话是用户主动点击软件盘上的向下收起按钮或完成按钮后软件盘会收起来。

但是有时候我们有这样的需求,比如说点击某个按钮弹出软键盘,点击另一个按钮收起软键盘。这是候就需要通过InputMethodManager来实现。

先看下实现的效果:

imgClick and drag to move

弹出软键盘

1
2
3
4
5
6
7
public static void showSoftInput(Context context, View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (view != null && imm != null){
imm.showSoftInput(view, 0);
// imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); // 或者第二个参数传InputMethodManager.SHOW_IMPLICIT
}
}

Click and drag to move

需要注意的是传入的View必须是Editext等能够获取焦点接收软件盘输入的控件才有效果,比如传入Button控件的话就无法弹出软键盘。

对于InputMethodManager.showSoftInput(View view, int flags)方法的第二个参数,看源码注释说可以传入0或者InputMethodManager.SHOW_IMPLICIT。我实际测试都可以弹出软键盘,目前还未发现有何区别。

该方法源码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* Synonym for {@link #showSoftInput(View, int, ResultReceiver)} without
* a result receiver: explicitly request that the current input method's
* soft input area be shown to the user, if needed.
*
* @param view The currently focused view, which would like to receive
* soft keyboard input.
* @param flags Provides additional operating flags. Currently may be
* 0 or have the {@link #SHOW_IMPLICIT} bit set.
*/
public boolean showSoftInput(View view, int flags) {
return showSoftInput(view, flags, null);
}

Click and drag to move

收起软键盘

1
2
3
4
5
6
7
public static void hideSoftInput(Context context, View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (view != null && imm != null){
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
// imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY); // 或者第二个参数传InputMethodManager.HIDE_IMPLICIT_ONLY
}
}

Click and drag to move

收起软键盘传入的View参数没要求一定要是Edittext,只要是当前页面的任意View都可以,比如我传入DecorView照样可以弹出软键盘hideSoftInput(context, getWindow().getDecorView())。

对于InputMethodManager.hideSoftInputFromWindow(IBinder windowToken, int flags)方法的第二个参数,看源码注释说可以传入0或者InputMethodManager.HIDE_IMPLICIT_ONLY。根据源码注释和测试可以知道这两者的区别:

  • 设置成0的话,不管软键盘是由用户点击Edittext后弹出的还是通过调用代码弹出的,都可以收起来。
  • 设置成InputMethodManager.HIDE_IMPLICIT_ONLY的话,用户点击Edittext弹出的软键盘可以收起来,但是通过代码弹出的软键盘无法收起。

InputMethodManager.hideSoftInputFromWindow的源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 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);
}

Click and drag to move